Reputation: 8379
Hi I want to iterate through only top level means child tags of a table.Below is my HTML
<table id="tab1">
---> <tr>
<td>
<table>
<tr><td></td></tr>
<tr><td></td></tr>
</table>
</td>
</tr>
---> <tr><td></td></tr>
---> <tr><td></td></tr>
</table>
If i iterate through all tr tags using the below code
$('#tab1 tr').each(function()
{
// This will iterate through all the <tr> ( 5 tags)..
});
But i want to iterate through the s which i have mentioned with > mark.. You can use the below fiddle to put hands on
http://jsfiddle.net/AzJRp/1/
Upvotes: 4
Views: 2155
Reputation: 7048
Based on the above answers/comments, I understand that most browsers may add tbody tag. I don't think it is good idea to add tbody programmatically to make it work with the selector '#tab1 > tbody > tr'.
Better to use Multiple selector to solve the issue. (I didn't test it. Hope somebody will test it and modify the answer or will add comment here.)
$('#tab1 > tbody > tr , #tab1 > tr').each(function() {
// ...
});
Upvotes: 1
Reputation: 19217
This will work:
$("#tab1 > tbody > tr").each(function(index, value) {
//this iterates through only 3 elements.
});
Upvotes: 0
Reputation: 434685
Some browsers will "correct" your HTML to include <tbody>
:
<table id="tab1">
<tbody>
<tr>
<td>
<!-- ... -->
</td>
</tr>
</tbody>
</table>
If possible, add the <tbody>
to your HTML yourself and then you can reliably use:
$('#tab1 > tbody > tr').each(function() {
// ...
});
Demo: http://jsfiddle.net/Qw2CJ/
If you don't insert the <tbody>
yourself, $('#tab1 > tr')
would work in some browsers and others would require $('#tab1 > tbody > tr')
. If you add the <tbody>
yourself, you can use the same simple CSS selector everywhere.
Upvotes: 5