如何通过 jQuery 函数只获得直接子元素

我有一个这样的表格结构:

<table1>
<tbody>
<tr>
<td></td>
...
<td>
<table2>
<tbody>
<tr>
<td></td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>

在 javascript 中,我有一个值为 $(table1)的变量 tbl,然后我想得到 table1<tbody>的所有直接子元素(tr)。 我的代码是:

$('tr', tb1)

显然,它返回了 table1和 table2中的所有 <tr>元素。 我想我可以过去

$('tr', tb1).not(function(){return $(this).parent().parent()[0] != tb1;})

或者这种逻辑。

我知道 $('table1 > tbody > tr')可以得到直接子 tr。不幸的是,我不能使用这个。

有人有什么好主意吗?

谢谢。

89190 次浏览

You can use find():

tbl.find("> tbody > tr")

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.

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/

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/