admin管理员组

文章数量:1431720

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?

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?

Share Improve this question asked Dec 8, 2016 at 4:20 JPGJPG 1,2555 gold badges32 silver badges69 bronze badges 5
  • 2 You forgot <tbody>. Use $('table > tbody').children('tr').length; – Tushar Commented Dec 8, 2016 at 4:21
  • Where's your HTML? – StackSlave Commented Dec 8, 2016 at 4:26
  • thanks @Tushar , your solution worked. But I want to know why is it so. I have not included tbody in my table element. then why should I use this for getting children? – JPG Commented Dec 8, 2016 at 4:26
  • $("table tbody tr").length; – Sreepathy Sp Commented Dec 8, 2016 at 4:28
  • 1 Why do browsers insert tbody element into table elements? – Tushar Commented Dec 8, 2016 at 4:29
Add a ment  | 

5 Answers 5

Reset to default 4

Try this

$("table tr").length;

If you only want to get tr within tbody

$("table tbody tr").length;

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.

Here is your answer.

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

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

Use this

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

OR

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

本文标签: javascripthow to get number of children in html table using jqueryStack Overflow