Reputation: 57986
How do I get the immediate children when searching for a particular element? For example, I want to get the tr
elements for the table t1
.
<table id="t1" bgcolor="yellow">
<tbody>
<tr>
<td>This is Cell 1</td>
<td>This is Cell 2</td>
</tr>
<tr>
<td>This is Cell 3</td>
<td>
<table id="t2" bgcolor="red">
<tbody>
<tr>
<td>This is Cell 1</td>
<td>This is Cell 2</td>
</tr>
<tr>
<td>This is Cell 3</td>
<td>This is Cell 4</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
I tried this:
'Count = ' + $('#t1 tbody').children('tr').length;
However, I get a count of 4, I don't understand why?
Here is a full example:
Upvotes: 1
Views: 1123
Reputation: 196306
That is because with $('#t1 tbody')
you get the tbody
from both tables
You could use directly the Child Selector (“parent > child”)
docs
$('#t1 > tbody > tr').length;
and here is you updated example: http://jsfiddle.net/SvygZ/1/
Upvotes: 1
Reputation: 349262
Use:
'Count = ' + $('#t1 > tbody').children('tr').length;
// or: $("#t1 > tbody > tr").length
// or: $("#t1")[0].rows.length; // In this case, equal to previous code.
// Warning: This also includes the rows from
// the <thead> and <tfoot> sections.
Your current code shows 4, because you have got two <tbody>
elements in the table #t1
:
<table id="t1" bgcolor="yellow"> <-- #t1
<tbody> <--- tbody
<tr> ... </tr> <----- Child 1
<tr> ... <----- Child 2
<tbody> <--- tbody (unexpected?)
<tr> ... </tr> <----- Child 3
<tr> ... </tr> <----- Child 4
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
Upvotes: 5