问题
I have a table structure like this:
<table1>
<tbody>
<tr>
<td></td>
...
<td>
<table2>
<tbody>
<tr>
<td></td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
In javascript, I have a variable tbl
with value of $(table1)
, and then I want to get all direct child elements (tr) of <tbody>
of table1
.
My code is :
$('tr', tb1)
Apparently it returns all <tr>
elements in table1 and table2.
I think I can get by
$('tr', tb1).not(function(){return $(this).parent().parent()[0] != tb1;})
or this kind of logic.
I know $('table1 > tbody > tr')
can get the direct child tr
. Unfortunately I can not use this.
Anyone has good idea about this?
Thanks.
回答1:
You can use find():
tbl.find("> tbody > tr")
回答2:
As @jave.web mentioned in the comments
To search through the direct children of an element use .children()
. It will only search through the direct children and not traverse any deeper. http://api.jquery.com/children/
回答3:
This is exactly the reason why one should be careful with nesting tables. I really hope that you use them for data and not page layout.
Another issue that will probably ruin your day is using CSS selectors on nested tables... you basically have the same issue - you are unable to select TR elements of the outer table without selecting those inside the inner table, too. (You cannot use the child selector because it is not implemented in IE6)
This should work:
$("#table1 > tbody > tr")
However, I recommend that you hardcode the TBODY element, since you should not rely on the browser to create it for you.
回答4:
http://api.jquery.com/child-selector/
$('tb1 > tr')
回答5:
If you have ids of both elements and you want to find direct element use below code
$("#parent > #two")
If you want a nested search you can use find. It is explained in detail here. https://handyopinion.com/jquery-selector-find-nested-child-elements/
来源:https://stackoverflow.com/questions/3687637/how-to-get-only-direct-child-elements-by-jquery-function