开发者

Selecting non-nested subnodes with JQuery

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?


function getOuterContainers(el) {

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

}

check it out: http://jsfiddle.net/GZ3Tx/


Try using jQuery's filter() method:

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

Basically, it finds all items with class .container below your top .container and filters the set based on whether or not the direct parent has the class .container.

See here for a working example: http://jsfiddle.net/TzL8Z/1


A solution working with arbitrary starting nodes:

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

Example: http://jsfiddle.net/tejp/GSRH2/2/

The advantage is that this works with an arbitrary starting node that doesn't need to be selectable with a simple JQuery selector, like it is the case in some of the other answers. Also it doesn't require "manually" walking over the whole tree with children().

The approach can also be easily extended to similar problems, like for example getting all .items not nested into a .container.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜