tags:

views:

16979

answers:

3

How do I count the number of tr elements within a table using jquery. Sorry, I sense this might be basic but i've been banging my head against it.

I know there is a similar thread, but I just want the total rows. http://stackoverflow.com/questions/613024/count-number-of-table-rows-between-two-specific-rows-with-jquery

+51  A: 

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

var rowCount = $('#myTable tr').length;
tvanfosson
$('#myTable tr').size() will return the same value.
Garry Shutler
@Garry -- the docs indicate that length is preferred over size() because it's faster.
tvanfosson
.size() calls .length internally
redsquare
I've always wondered what the point of the size method was. Did length not exist originally and it's just there for backward compatibility?
Matthew Crumley
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.
tvanfosson
+11  A: 

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;
James Moberg
A: 

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.

jjroman