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 | Price |
|---|---|
| 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
tdorthoutsidetr. Cells belong inside a row. - Using
trto make columns or spacing on a page. Use CSS for page layout. - Making a cell look like a heading with styling alone. Use
thand, when useful, itsscopeattribute. - 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
- For groups of data rows, see How to Use the tbody Element.
- For total or summary rows, see How to Use the tfoot Element.
- For the whole table, see How to Use the table Element.
- For heading and data cells, see th and td.
- For tr rules, DOM API, and browser or accessibility evidence, see tr in Yugien Atlas.