Toran Billups
Toran Billups

Reputation: 27399

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

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

Upvotes: 4

Views: 13392

Answers (6)

bobince
bobince

Reputation: 536449

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.

Upvotes: 4

Ash
Ash

Reputation: 62116

Try:

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

Using > may not work if you use a tbody, thead etc.

Also, the # will select an element, any element, with an id of table. Just be sure this is what you want.

Upvotes: 2

Miles
Miles

Reputation: 32478

Browsers automatically add a tbody element to the DOM.

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

The "table tr" answers posted will not work correctly with nested tables.

Upvotes: 2

garrow
garrow

Reputation: 3489

Without the descendant selector works for me, but not with.
works:

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

doesnt:

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

Also make sure you put the declaration inside the docready or it wont work.

$(document).ready(function() {
     var trCount = $("table tr").size();
});

Upvotes: 2

alphadogg
alphadogg

Reputation: 12900

It should work, but I believe what you want is:

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

If you use #table, you're asking for a table with id='table' which I guess is an error?

Upvotes: 1

David Brown
David Brown

Reputation: 36239

This should work:

var count = $("#table tr").length;

Upvotes: 12

Related Questions