Jason Kelly
Jason Kelly

Reputation: 2655

Counting the number of rows in an HTML table except don't count the <th></th> 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 <th></th> as a row itself?

var rows = document.getElementById("data").rows.length;

Upvotes: 2

Views: 2110

Answers (4)

Felipe Oriani
Felipe Oriani

Reputation: 38608

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);

Upvotes: 3

Silviu Burcea
Silviu Burcea

Reputation: 5348

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();

Upvotes: 0

suff trek
suff trek

Reputation: 39777

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/

Upvotes: 0

epascarello
epascarello

Reputation: 207511

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

Upvotes: 3

Related Questions