递归搜索顶级匹配元素

Recursively searching for top level of matching elements

本文关键字:元素 搜索 递归      更新时间:2023-09-26

假设我有一些HTML,如下所示,并且我想搜索具有foo类的#top元素的后代。然而,我只想找到不是我找到的其他元素的子元素的元素。也就是说,尽管通常我想递归地搜索foo元素,但我不想递归到foo元素中。

<div class="foo" id="top">
    <div class="bar">
        <div class="foo"> <!-- Find this !-->
        </div>
    </div>
    <div class="foo"> <!-- Find this !-->
        <div class="foo"> <!-- Do not find this, because we already found parent !-->
        </div>
    </div>
</div>

我怎样才能最好地使用Javascript/jQuery?

编辑:对此有些困惑。上面的例子是为了说明这个问题,但它并没有封装通用解决方案应该解决的每个边缘情况,所以我在这里创建了一个更复杂的例子:http://jsfiddle.net/JQNyW/1/

这样?

$('#top').find('.foo').filter(function () { // while selecting ignore parent which also has foo
    return $(this).parents('.foo').length == 1; //length is 1 since the #top also has foo
});

Fiddle

$('#top').find('.foo').filter(function () {
    return $(this).parents('.foo:not("#top")').length == 0
}).css('color', 'red');

我可能会单独使用children()或find(

 $('#top').children('.foo').attr('this','yeah');
 $('#top').find('> .foo',this).attr('child','yes');

在控制台中,它只将att()添加到第一个元素中。

根据您的需要,请参阅jQuery:中的文档

http://api.jquery.com/find/

http://api.jquery.com/children/

希望这能有所帮助。

您可以使用以下选择器:

#top > .foo, :not(.foo) > .foo

无论是在jQuery中还是在原生JavaScript中。