JPG
JPG

Reputation: 1253

how to get number of children in html table using jquery

I am not able to understand the behavior of jquery method children. I am able to count the number of <p> in a <div> using :

   var abc = $("div").children("p");
   alert(abc.length);

But the same thing when applied to <tr> within <table> results in 0 (zero) count.

   var abc = $("table").children("tr");
   alert(abc.length);

why is it so?

Upvotes: 2

Views: 2956

Answers (5)

user9534295
user9534295

Reputation:

Use this

var childrensCount = $('table tr').length;

OR

var childrensCount = $('#tableId tr').length;

Upvotes: 0

sam
sam

Reputation: 969

children() will return direct children (traverses single level) of <table> but not the grand-child(ie, children's children).

If you wish to search in descendants of an element, use find().

Here is how then you can get the <tr> of <table>:

var trs = $('table').find('tr');

And, to get the count/length

alert($('table').find('tr').length);  


No nested table
If there is no nested tables, then

alert($('table').find('tr').length);

or

alert($('table tr').length);

will give you a proper result.


Nested tables
If you are having some nested tables i.e <table> inside a <table>,

Above code won't give you correct result, if you need <tr>s of parent <table>, but not of children <table>.

Here is how then you can get it:

alert($('table>tbody>tr').length);

or

alert($('table').children('tbody').children('tr').length);

Hope it helps.

Upvotes: 1

user3146115
user3146115

Reputation:

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

var tableRowCount = $('table tr').length;

This approach also used for get counts all trs of every nested table

Upvotes: 0

Jaber
Jaber

Reputation: 277

Here is your answer.

alert($("table tr").length);

Upvotes: 0

Mairaj Ahmad
Mairaj Ahmad

Reputation: 14604

Try this

$("table tr").length;

If you only want to get tr within tbody

$("table tbody tr").length;

Upvotes: 4

Related Questions