HTML / Element

How to Use the tr Element

The tr element makes one row in a table. Inside it, place heading cells with th and data cells with td.

The short answer

Use tr for a table row, then put its cells inside that row. Use th for a heading and td for a value or description.

tr is not a box for arranging the page. Use it for data that belongs in table rows and columns.

A small example

<table>
  <caption>Fruit prices</caption>
  <thead>
    <tr>
      <th scope="col">Fruit</th>
      <th scope="col">Price</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th scope="row">Apples</th>
      <td>$1.20</td>
    </tr>
    <tr>
      <th scope="row">Oranges</th>
      <td>$0.80</td>
    </tr>
  </tbody>
</table>
Fruit prices
FruitPrice
Apples$1.20
Oranges$0.80

Each tr is one row. The first row names the columns, and the next rows show a fruit and its price.

Rows and row groups

thead, tbody, and tfoot group the heading, main, and summary parts of a table. A tr is a row inside one of those groups. Giving the parts a clear structure makes the table easier to follow.

If you write a tr directly under table, the HTML parser adds an implicit tbody to the DOM. This means the DOM seen by JavaScript can differ a little from the source text. When writing new markup, include tbody yourself.

Inspect a row with JavaScript

rowIndex is the row's position in the whole table. sectionRowIndex is usually its position inside its row group. Both start at zero. If JavaScript makes a row a direct child of the table, sectionRowIndex also uses the table's row list. The cells collection contains the row's direct th and td cells.

const row = document.querySelector("tbody tr");
row.rowIndex;         // Position in the whole table
row.sectionRowIndex;  // Position in this tbody
row.cells.length;     // Number of cells in this row

insertCell() can add a cell. With no argument, it adds a td at the end of the row. It does not create a heading cell for you, so write a th in the HTML when the new cell is a heading.

Common mistakes

  • Putting td or th outside tr. Cells belong inside a row.
  • Using tr to make columns or spacing on a page. Use CSS for page layout.
  • Making a cell look like a heading with styling alone. Use th and, when useful, its scope attribute.
  • Leaving out end tags until row boundaries are hard to see. The end tag can be omitted in some cases, but writing </tr> is clearer while learning.

Related pages