Skip to content Skip to sidebar Skip to footer

Counting The Number Of Rows In An HTML Table Except Don't Count The As A Row

I need your help, if the following code below counts every table row in a table, how can it be amended such that the code won't count the as a row itself? var

Solution 1:

You should be using thead and tbody

HTML:

<table id="data">
    <thead>
        <tr><th>Hz</th></tr>
    </thead>
    <tbody>
        <tr><td>1</td></tr>
        <tr><td>2</td></tr>
        <tr><td>3</td></tr>
    </tbody>
</table>

JavaScript:

var rows = document.getElementById("data").getElementsByTagName("tbody")[0].rows.length;

JSFiddle


Solution 2:

Take a look at this JSFiddle, the code I tried is:

var rows = document.getElementById('data').getElementsByTagName('tr');
var count = 0;
for(var i = 0; i < rows.length; i++)
{    
    if (rows[i].getElementsByTagName('th').length == 0)
        count++;
}
alert(count);

Solution 3:

Without modifying your HTML markup you have to count the correct rows yourself:

var rows = document.getElementById("data").rows
var count = 0;
for (var i=0; i< rows.length; i++) {
    if (rows[i].cells[0].tagName != 'TH') count++
}
console.log(count)

Demo: http://jsfiddle.net/cHW6z/


Solution 4:

With the love of jQuery, if you don't want to do it with pure JS:

$('#tableId tr').filter(function() { 
    return $(this).find('th').size() == 0;
}).size();

Post a Comment for "Counting The Number Of Rows In An HTML Table Except Don't Count The As A Row"