ChatGPT解决这个技术问题 Extra ChatGPT

jQuery: count number of rows in a table

How do I count the number of tr elements within a table using jQuery?

I know there is a similar question, but I just want the total rows.


C
Community

Use a selector that will select all the rows and take the length.

var rowCount = $('#myTable tr').length;

Note: this approach also counts all trs of every nested table!


$('#myTable tr').size() will return the same value.
@Garry -- the docs indicate that length is preferred over size() because it's faster.
.size() calls .length internally
It has a length property because it's an array. I don't know enough of the history of jQuery to know whether the jQuery object always extended an array.
This will also count tr in the thead... $('#myTable tbody tr').length; will count those only in table bodies..
J
James Moberg

If you use <tbody> or <tfoot> in your table, you'll have to use the following syntax or you'll get a incorrect value:

var rowCount = $('#myTable >tbody >tr').length;

I'm using but I get the same value
use $('#myTable >tbody:last >tr').length;
@DevlshOne That is not true, length is not zero base, check the documentation: api.jquery.com/length
When you have nested tables, this will only count the rows in the specified table, which is what I needed.
@user12379095 Something like this: stackoverflow.com/questions/32101764/…
D
DevlshOne

Alternatively...

var rowCount = $('table#myTable tr:last').index() + 1;

jsFiddle DEMO

This will ensure that any nested table-rows are not also counted.


Oh, because then index returns -1. Clever.
Thanks. They are few and far between but clever solutions do slip out now and again.
var rowCount = $('table#myTable tr:last').index() + 1;
Ignores <thead> rows and nested table rows. Nice. jsfiddle.net/6v67a/1576
If Last <td> has inner table, it returns row count of that table!! jsfiddle.net/6v67a/1678
P
Peter Ajtai

Well, I get the attr rows from the table and get the length for that collection:

$("#myTable").attr('rows').length;

I think that jQuery works less.


+1 - Good for the scenario where you are passed element that contains a table eg var rowCount = $(element).attr('rows').length;
Using JQuery v1.9.0 and I must use prop() to access 'rows': $("#myTable").prop('rows').length; (Chromium 24)
M
McGarnagle

Here's my take on it:

//Helper function that gets a count of all the rows <TR> in a table body <TBODY>
$.fn.rowCount = function() {
    return $('tr', $(this).find('tbody')).length;
};

USAGE:

var rowCount = $('#productTypesTable').rowCount();

Very nice function @Ricky G, useful to do several things example this function can be called for html generated from backend instead of dom as well.. Thanks
c
chifliiiii

I got the following:

jQuery('#tableId').find('tr').index();

plus 1 to get the number of rows
B
BornToCode

try this one if there is tbody

Without Header

$("#myTable > tbody").children.length

If there is header then

$("#myTable > tbody").children.length -1

Enjoy!!!


It is missing () after chidlren => $("#myTable > tbody").children().length
The header should be enclosed in <thead> which should come before <tbody>. So the -1 should not be needed, if the table is properly designed according to the standard.
problem is , when datatable has no record it shows length as 1, because datatable render a empty row with class "odd" in datatable .....
I have a dynamic table on a UserScript and this was the only solution that worked
d
dennismonsewicz

I needed a way to do this in an AJAX return, so I wrote this piece:

<p id="num_results">Number of results: <span></span></p>

<div id="results"></div>

<script type="text/javascript">
$(function(){
    ajax();
})

//Function that makes Ajax call out to receive search results
var ajax = function() {
    //Setup Ajax
    $.ajax({
        url: '/path/to/url', //URL to load
        type: 'GET', //Type of Ajax call
        dataType: 'html', //Type of data to be expected on return
        success: function(data) { //Function that manipulates the returned AJAX'ed data
            $('#results').html(data); //Load the data into a HTML holder
            var $el = $('#results'); //jQuery Object that is holding the results
            setTimeout(function(){ //Custom callback function to count the number of results
                callBack($el);
            });
        }
    });
}

//Custom Callback function to return the number of results
var callBack = function(el) {
    var length = $('tr', $(el)).not('tr:first').length; //Count all TR DOM elements, except the first row (which contains the header information)
    $('#num_results span').text(length); //Write the counted results to the DOM
}
</script>

Obviously this is a quick example, but it may be helpful.


Z
Zoe

I found this to work really well if you want to count rows without counting the th and any rows from tables inside of tables:

var rowCount = $("#tableData > tbody").children().length;

How to modify it to count columns?
C
Cybernetic
row_count =  $('#my_table').find('tr').length;
column_count =  $('#my_table').find('td').length / row_count;

O
Olamigoke Philip

var trLength = jQuery('#tablebodyID >tr').length;


H
Hasan Zafari

document.getElementById("myTable").rows.length;