JavaScript to get rows count of a HTML table
How to get with JavaScript the rows count of a HTML table
having id and name?
Given a
<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>
and a
var table = document.getElementById("tableId");
there are two ways to count the rows:
var totalRowCount = table.rows.length; // 5
var tbodyRowCount = table.tBodies[0].rows.length; // 3
The table.rows.length
returns the amount of ALL <tr>
elements within the table. So for the above table it will return 5
while most people would really expect 3
. The table.tBodies
returns an array of all <tbody>
elements of which we grab only the first one (our table has only one). When we count the rows on it, then we get the expected value of 3
.
You can use the .rows
property and check it's .length
, like this:
var rowCount = document.getElementById('myTableID').rows.length;
$('tableName').find('tr').length
If the table has an ID
:
const tableObject = document.getElementById(tableId);
const rowCount = tableObject[1].childElementCount;
If the table has a Class
:
const tableObject = document.getElementsByClassName(tableClass);
const rowCount = tableObject[1].childElementCount;
If the table has a Name
:
const tableObject = document.getElementsByTagName('table');
const rowCount = tableObject[1].childElementCount;
Note: index 1
represents <tbody>
tag