jQuery: count number of rows in a table

Viewed 799741

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.

12 Answers

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!

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;

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

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

Related