Counting the number of rows in an HTML table except don't count the <th></th> as a row

我与影子孤独终老i 提交于 2019-12-11 03:02:03

问题


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;

回答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




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



回答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/




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


来源:https://stackoverflow.com/questions/20501568/counting-the-number-of-rows-in-an-html-table-except-dont-count-the-th-th-as

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!