附加到选择器匹配的最外层元素

时间:2011-08-29 15:37:35

标签: jquery jquery-selectors

我的文档中有一个表,可能包含也可能不包含多个嵌套表。每个表(外部和可能的内部)都包含tbody标记。我想匹配最外面的tbody标签。

以下是示例文档:

<table id="shippingContainer">
    <thead>
    </thead>
    <tbody>
        <tr>
            <td>
            </td>
        </tr>
        <tr>
            <td>
                <table>
                    <tbody>
                    </tbody>
                </table>
            </td>
        </tr>
</table>

在这种情况下,我有JQuery选择器选择最外面的表。我想选择与该表关联的tbody元素,但不要选择嵌套表中的任何tbody元素。

我原来的选择器很简单:

$("#shippingContainer").find("tbody");

由于显而易见的原因,这不起作用。谢谢你的帮助!

4 个答案:

答案 0 :(得分:5)

您可以使用child selector来实现:

$("#shippingContainer > tbody");

这将匹配您的表的直接子项的<tbody>元素。

答案 1 :(得分:0)

您可以使用子选择器,如下所示:

这将选择shippingContainer表中的第一个tbody元素:

//This will select the first tbody element (of your main table)
$("#shippingContainer > tbody")

这将选择主表中的嵌套tbody元素:

//This will select the tbody element within the table (the inner table)
$("#shippingContainer").find('table > tbody')

Read more on child selectors here

答案 2 :(得分:0)

使用children代替find

$("#shippingContainer").children("tbody");

答案 3 :(得分:0)

你也可以这样做:

$("#shippingContainer").find("tbody").first();
相关问题