Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting the number of rows in a table NOT using jquery

Tags:

javascript

<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>
like image 209
phpmeh Avatar asked Dec 03 '11 17:12

phpmeh


2 Answers

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;
like image 81
Felix Kling Avatar answered Oct 17 '22 19:10

Felix Kling


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.

like image 40
Madara's Ghost Avatar answered Oct 17 '22 20:10

Madara's Ghost