Sometimes, we want to get the row count of a HTML table with JavaScript.
In this article, we’ll look at how to get the row count of a HTML table with JavaScript.
How to get the row count of a HTML table with JavaScript?
To get the row count of a HTML table with JavaScript, we can use the rows
property.
For instance, we write
<table id="tableId">
<thead>
<tr>
<th>Header</th>
</tr>
</thead>
<tbody>
<tr>
<td>Row 1</td>
</tr>
<tr>
<td>Row 2</td>
</tr>
<tr>
<td>Row 3</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>Footer</td>
</tr>
</tfoot>
</table>
to add a table.
Then we write
const table = document.getElementById("tableId");
const totalRowCount = table.rows.length;
const tbodyRowCount = table.tBodies[0].rows.length;
to select the table with getElementById
.
Then we use table.rows.length
to get a node list of all tr elements in the table.
We use tBodies[0]
to get the first tbody element in the table.
And we use rows
to get all tr elements in the tbody element.
We get the count of each with length
.
Conclusion
To get the row count of a HTML table with JavaScript, we can use the rows
property.