HTML DOM TableRow Object: A Comprehensive Guide

The HTML DOM TableRow object represents an <tr> element in an HTML table. This object allows you to access and manipulate the properties and methods of table rows using JavaScript. This guide will provide a detailed overview of the TableRow object, covering its properties, methods, and practical examples.

Understanding the TableRow Object

The TableRow object is part of the HTML DOM (Document Object Model), which represents the structure of an HTML document as a tree-like structure. Each HTML element is represented as an object, and the TableRow object specifically represents a row within a table.

Purpose of the TableRow Object

The primary purpose of the TableRow object is to enable developers to:

  • Access individual table rows within an HTML table.
  • Get and set properties of table rows (e.g., background color, alignment).
  • Add, remove, or modify table cells within a row.
  • Programmatically interact with table rows to create dynamic tables.
  • Handle events on specific rows for enhanced interactivity.

Accessing Table Rows

To work with table rows, you first need to access them using JavaScript. You can access a table row using methods like rows, getElementsByTagName, or by directly accessing them using their ID or class, if set.

Accessing Rows Using the rows Collection

The rows property of the <table> object returns an HTMLCollection of all the <tr> elements in a table.

<table id="myTable1">
    <tr><td>Row 1 Cell 1</td><td>Row 1 Cell 2</td></tr>
    <tr><td>Row 2 Cell 1</td><td>Row 2 Cell 2</td></tr>
    <tr><td>Row 3 Cell 1</td><td>Row 3 Cell 2</td></tr>
</table>

<script>
    const table1 = document.getElementById('myTable1');
    const rows1 = table1.rows;

    console.log('Number of rows:', rows1.length); // Output: 3
    console.log('First row:', rows1[0]);         // Output: The first <tr> element
    console.log('Second row:', rows1[1]);        // Output: The second <tr> element

    // You can also access cells of a row using cells property
    const cells_row_1 = rows1[0].cells;
    console.log('Cells in the first row:', cells_row_1);
    console.log('First cell in first row:', cells_row_1[0]);
</script>

The rows property provides an easy way to access all the rows within a table and access it’s cell too using cells property.

Accessing Rows Using getElementsByTagName()

You can also access table rows using the getElementsByTagName() method on the table element.

<table id="myTable2">
    <tr><td>Row 1 Cell 1</td><td>Row 1 Cell 2</td></tr>
    <tr><td>Row 2 Cell 1</td><td>Row 2 Cell 2</td></tr>
    <tr><td>Row 3 Cell 1</td><td>Row 3 Cell 2</td></tr>
</table>

<script>
  const table2 = document.getElementById('myTable2');
  const rows2 = table2.getElementsByTagName('tr');

    console.log('Number of rows:', rows2.length); // Output: 3
    console.log('First row:', rows2[0]);         // Output: The first <tr> element
    console.log('Second row:', rows2[1]);        // Output: The second <tr> element
</script>

The getElementsByTagName('tr') method provides an alternative way to retrieve the rows from a table as an HTMLCollection.

Accessing Rows by ID or Class

If the <tr> element has an ID or class, you can access it directly using methods like getElementById() or getElementsByClassName().

<table id="myTable3">
    <tr id="row1"><td>Row 1 Cell 1</td><td>Row 1 Cell 2</td></tr>
    <tr class="row-class"><td>Row 2 Cell 1</td><td>Row 2 Cell 2</td></tr>
    <tr><td>Row 3 Cell 1</td><td>Row 3 Cell 2</td></tr>
</table>

<script>
    const row1 = document.getElementById('row1');
    const row2 = document.getElementsByClassName('row-class')[0];
    console.log('Row with ID row1:', row1);       // Output: The <tr> element with ID 'row1'
    console.log('Row with class row-class:', row2); // Output: The <tr> element with class 'row-class'
</script>

This method of accessing table rows is very specific to the id and class of the row, making it useful when you want to access a specific row from the table.

Properties of the TableRow Object

The TableRow object has several properties that provide information about the table row or allow manipulation of the row:

`, `

`, or `

`), starting from 0.
Property Type Description
`cells` HTMLCollection Returns a collection of the table cells (`

` elements) in the row.
`rowIndex` Number Returns the index of the row within the table’s `rows` collection, starting from 0.
`sectionRowIndex` Number Returns the index of the row within its table section (`

`align` String Sets or returns the horizontal alignment of the content within the row (`left`, `center`, `right`, `justify`, or `char`).
`bgColor` String Sets or returns the background color of the row.
`ch` String Sets or returns the alignment character for cells within the row. (Deprecated in HTML5)
`chOff` String Sets or returns the offset of the alignment character for cells within the row. (Deprecated in HTML5)
`vAlign` String Sets or returns the vertical alignment of the content within the row (`top`, `middle`, `bottom`, or `baseline`).
`offsetHeight` Number Returns the offset height of the element.
`offsetLeft` Number Returns the offset left of the element.
`offsetTop` Number Returns the offset top of the element.
`offsetWidth` Number Returns the offset width of the element.
`parentElement` Object Returns the parent element of the row.
`innerHTML` String Sets or returns the HTML content of a row element.

Note: Properties such as ch and chOff are deprecated in HTML5 and might not work as expected in modern browsers. It is recommended to use CSS for styling purposes. ⚠️

Methods of the TableRow Object

The TableRow object has several methods that enable you to modify the table row dynamically:

Method Description
`insertCell()` Inserts a new table cell (`

`) into the row at the specified position.
`deleteCell()` Removes a table cell from the row at the specified position.

insertCell() Method

This method creates a new cell in the table row.

<table id="myTable4">
    <tr id="row-insert"><td>Cell 1</td><td>Cell 2</td></tr>
</table>

<button onclick="insertCell()">Insert Cell</button>

<script>
    function insertCell() {
      const row_insert = document.getElementById('row-insert');
      const newCell = row_insert.insertCell(1);
      newCell.textContent = 'New Cell';
    }
</script>

Clicking on the button will insert a new cell at the index 1 of the first row.

deleteCell() Method

This method deletes an existing cell of a table row.

<table id="myTable5">
    <tr id="row-delete"><td>Cell 1</td><td>Cell 2</td><td>Cell 3</td></tr>
</table>

<button onclick="deleteCell()">Delete Cell</button>

<script>
  function deleteCell() {
    const row_delete = document.getElementById('row-delete');
    row_delete.deleteCell(1);
  }
</script>

Clicking the button will remove cell at the index 1 from the first row.

Practical Examples

Example 1: Changing Row Background Color

<table id="myTable6">
  <tr id="row-bg-color"><td>Cell 1</td><td>Cell 2</td></tr>
</table>
<button onclick="changeRowColor()">Change Row Color</button>

<script>
  function changeRowColor() {
    const row_bg_color = document.getElementById('row-bg-color');
    row_bg_color.bgColor = 'lightgreen';
  }
</script>

Clicking the button will change the background color of the row.

Example 2: Accessing Cells within a Row

<table id="myTable7">
    <tr id="row-cells"><td>Cell 1</td><td>Cell 2</td><td>Cell 3</td></tr>
</table>
<script>
  const row_cells = document.getElementById('row-cells');
  const cells7 = row_cells.cells;

  console.log('Number of cells:', cells7.length);
  cells7[0].textContent = 'Updated Cell 1';
</script>

This example shows how to access cells in a row and change their text content.

Example 3: Row Index

<table id="myTable8">
    <tr><td>Row 1</td></tr>
    <tr><td>Row 2</td></tr>
    <tr id="row-index"><td>Row 3</td></tr>
</table>

<script>
    const row_index = document.getElementById('row-index');
    console.log('Row index:', row_index.rowIndex); // Output: 2
</script>

This example demonstrates accessing the index of the row within the table.

Example 4: Adding Dynamic Content to row

<table id="myTable9">
    <tr id="dynamic-row"><td>Initial Cell</td></tr>
</table>

<button onclick="addContent()">Add Content</button>

<script>
    function addContent() {
      const dynamic_row = document.getElementById('dynamic-row');
      dynamic_row.innerHTML = '<td>New Cell 1</td><td>New Cell 2</td>';
    }
</script>

Clicking the button will update the row’s inner HTML, replacing existing content.

Browser Support

The TableRow object and its methods are widely supported in all modern browsers.

Note: Always test your code in multiple browsers to ensure compatibility and consistent behavior. ✅

Conclusion

The HTML DOM TableRow object is a powerful tool for interacting with table rows in JavaScript, allowing you to create dynamic and interactive tables. Understanding and utilizing its properties and methods can significantly enhance your ability to manipulate HTML tables programmatically. This guide covered all the essentials, making it easier to implement complex functionalities in your web development projects. With the help of this comprehensive guide, you can now confidently use TableRow objects in your web development tasks.