Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using jQuery to find the number of TR elements in a given table

Tags:

jquery

I have seen several examples on how to find children, etc but for some reason I can't get this one right ... any help from the SO community?

The below is my current "attempt" in code --

var trCount = $("#table > tr").size();

like image 599
Toran Billups Avatar asked Nov 29 '22 21:11

Toran Billups


2 Answers

This should work:

var count = $("#table tr").length;
like image 115
David Brown Avatar answered Dec 11 '22 04:12

David Brown


Plain Old DOM:

document.getElementById('table').rows.length;

is going to be much more efficient than asking jQuery to go work out the selector and return every row element for you.

You don't have to force everything you do into a jQuery-shaped hole; sometimes the old ways are still the best. jQuery was created to supplement JavaScript in the areas it was weak, not completely replace the entire language.

$("#table tr").size();

Fails for nested tables.

$("#table > tr").size();

Fails for tr in tbody (which is very often the case as they can get inserted automatically).

$("#table > tbody > tr").size();

Fails for tr in thead/tfoot.

like image 22
bobince Avatar answered Dec 11 '22 02:12

bobince