2

I have a HTML structure that contains nested divs with the container class:

<div class="container" id="0">
  <div id="1">
    <div class="container" id="2">
      <div class="container" id="3"></div>
    </div>
    <div id="4">
      <div class="container" id="5"></div>
    </div>
  </div>
</div>

This could include more divs and deeper/different nesting.

Starting from some point in the tree I'd like to find all containers in that subtree that are not nested within other containers. So for example from div #1 I'd like to find the divs #2 and #5, but not #3 (since it is nested in container #2 already found).

What would be the best way to accomplish this?

4

3 回答 3

2

尝试使用 jQuery 的filter()方法:

$items = $('#0').find('.container').filter(function(index) {
    return !$(this).parents(':not(#0)').hasClass('container');
});

基本上,它会找到 class.container低于 top.container的所有项目,并根据直接父级是否具有 class 过滤集合.container

有关工作示例,请参见此处:http: //jsfiddle.net/TzL8Z/1

于 2011-01-18T19:21:12.103 回答
2
function getOuterContainers(el) {

    if (el.length == 0)
        return $([]);
    else
        return el.children('.container').add( getOuterContainers(el.children(':not(.container)')) );

}

看看:http: //jsfiddle.net/GZ3Tx/

于 2011-01-18T19:24:55.880 回答
0

使用任意起始节点的解决方案:

function getContainers(base) {
   return base.find('.container').not(base.find('.container .container'));
}

示例:http: //jsfiddle.net/tejp/GSRH2/2/

优点是这适用于不需要使用简单的 JQuery 选择器选择的任意起始节点,就像其他一些答案中的情况一样。此外,它不需要“手动”在整棵树上行走children()

该方法也可以很容易地扩展到类似的问题,例如让所有.items 不嵌套到 a.container中。

于 2011-01-19T18:12:08.103 回答