jQuery只获得顶级元素

Leb*_*ski 2 jquery nested

我只需要从我的树中获得第一个匹配的元素(如果发现元素不需要更深入).问题是这个元素可以包装成嵌套的div,所以我不能使用>selector.
我的代码是这样的:

<div id="root">
    <div class="sub">I need this element</div>
    <div>
        <div class="sub">I need this element</div>
    </div>
    <div class="sub">
        <div class="sub">I don't need this element</div>
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

找不到解决方案:(

Fel*_*ing 5

如果您无法使用子选择器,请尝试

$('.sub:not(.sub .sub)')
Run Code Online (Sandbox Code Playgroud)

这仅选择那些.sub不是其他.sub元素后代的元素.

或者:

$('#root .sub').filter(function() {
    return $(this).parentsUntil('#root', '.sub').length === 0;
});
Run Code Online (Sandbox Code Playgroud)

如果#root在里面也可以工作.sub.

编辑:或者看看@ RightSaidFred对此案例的评论.