Counting the number of rows in a table NOT using jquery
<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>
Try the following:
var rows = document.getElementById('myTableId').getElementsByTagName('tbody')[0].getElementsByTagName('tr').length;
It will count the number of <tr>
in <tbody>
, which in turn will be the number of rows in the table.
Note that it will not read all the rows in the table. tag only . If you have a <thead>
or <tfoot>
or even a line outside the body, it will not be counted.
Another way: rows
property [MDN] :
var num = document.getElementById('myTableId').rows.length;
If you only want to count the rows from the first tbody
element, first select it ( tbody
property [docs] )
var num = document.getElementById('myTableId').tBodies[0].rows.length;
Here is a working implementation:
var table = document.getElementById("myTableId"); var tbody = table.tBodies[0]; alert(tbody.rows.length);
And jsFiddle example: http://jsfiddle.net/9a6zK/
Try:
var numberOfRows = document.getElementById('myTableId').getElementsByTagName('tbody')[0].getElementsByTagName('tr').length;