How to get with JavaScript the rows count of a HTML table
having id and name?
This question is related to
javascript
html
$('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
This is another option, using jQuery and getting only tbody
rows (with the data) and desconsidering thead/tfoot
.
$("#tableId > tbody > tr").length
console.log($("#myTableId > tbody > tr").length);
_x000D_
.demo {
width:100%;
height:100%;
border:1px solid #C0C0C0;
border-collapse:collapse;
border-spacing:2px;
padding:5px;
}
.demo caption {
caption-side:top;
text-align:center;
}
.demo th {
border:1px solid #C0C0C0;
padding:5px;
background:#F0F0F0;
}
.demo td {
border:1px solid #C0C0C0;
text-align:left;
padding:5px;
background:#FFFFFF;
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="myTableId" class="demo">
<caption>Table 1</caption>
<thead>
<tr>
<th>Header 1</th>
<th>Header 2</th>
<th>Header 3</th>
<th>Header 4</th>
</tr>
</thead>
<tbody>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan=4 style="background:#F0F0F0"> </td>
</tr>
</tfoot>
</table>
_x000D_
You can use the .rows
property and check it's .length
, like this:
var rowCount = document.getElementById('myTableID').rows.length;
Source: Stackoverflow.com