<head>
<script language="javascript">
// must have the onload handler
onload = function countRows(){
var rows = document.getElementById('myTableId').getElementsByTagName('tbody')[0].rows.length;
alert( rows);
// outputs 3
}
</script>
</head>
<body>
<table id="myTableId">
<tbody>
<tr><td></td><td><input onclick="doA_Function_That_Includes_CountRows()" />
</td></tr>
<tr><td></td><td></td></tr>
<tr><td></td><td></td></tr>
</tbody>
</table>
</body>
</html>
Another way, using the rows
property [MDN]:
var num = document.getElementById('myTableId').rows.length;
If you only want to count the rows from the first tbody
element, select it first (tBody
property [docs])
var num = document.getElementById('myTableId').tBodies[0].rows.length;
Try this:
var rows = document.getElementById('myTableId').getElementsByTagName('tbody')[0].getElementsByTagName('tr').length;
http://jsfiddle.net/y8URn/
It will count the number of <tr>
s in the <tbody>
, which in turn will be the number of rows in the table.
Do note that it will NOT count all of the rows in the table only in the table body. If you have a <thead>
or a <tfoot>
or even a row outside of the tbody, it will not be counted.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With