Reputation: 1114
I have table within table scenario. When i try to select the trs using
$("#table tr");
then it select all the tr from inner tables also.
How can i select tr from outer table only.
Upvotes: 0
Views: 466
Reputation: 8939
There are two alternatives for selecting direct children in the table body with jQuery:
var rows = $('#table > tbody > tr');
or
var rows = $('#table').children('tbody').children('tr');
The tbody
element is created automatically in DOM (also in obsolete IE5.5), even when it was not written in HTML.
Using the jQuery's child selector is more readable and a bit faster than .children() method.
Upvotes: 0
Reputation: 5364
Use this instead:
$('#table > tr'); // choose direct child tr nodes from table with id 'table'
Or
$('#table > tbody > tr');
If you have tbody
element.
Here is link to jQuery documentation: http://api.jquery.com/child-selector/
Upvotes: 5
Reputation: 237817
Intuitively, it seems like
$('table.top > tr');
will be sufficient. However, you can't guarantee that it will be. Some browsers implicitly insert a tbody
element as a parent of all the tr
s. This is technically required by some versions of the HTML standard. Not all browsers do this, however. For safety, you should probably do something like this:
$('table.top > tr, table.top > thead > tr, table.top > tbody > tr');
A bit verbose, but more likely to work in more situations.
Upvotes: 1
Reputation: 3159
Yep:
$('#table > tr');
But also, if you are making stylistic changes, make sure that you set a base style to all the table rows first (or target the inner tables specifically).
For example, if you execute $("#table > tr").css("background-color", "orange");
, the inner tables will become orange as well, because by CSS properties they inherit their parent styles.
Set a base color for all table rows first:
tr {
background-color: white;
}
Upvotes: 0
Reputation: 13744
if you have multiple tables in a single page, give them classes so you don't have to go through this every other time..
e.g.
$('.mytable > tr')
html
<table class="mytable">
<tr>
<td>...</td>
</tr>
</table>
Upvotes: 0