25

I have a situation in which i need to select all descendants of a certain element, but exclude those that are children of a container that equals the CSS class of the container i run my selector on.

Pretty complicated description.

<div class="container">
   <div class="element"></div>
   <div class="element"></div>
   <div class="element"></div>
   <div class="element">
       <div class="container">
           <div class="element"></div>
           <div class="element"></div>
           <div class="element"></div>
       </div>
   </div>

Running a jQuery .find('.element') on the outermost DIV will get me all the DIVs, even the ones inside the second container. That is what i try to avoid.

Is there a quick and simple jQuery selector solution for this case?

2
  • Can you point to me which elements you want selected?
    – BoltClock
    Commented Nov 22, 2011 at 20:49
  • In this case, the 4 DIVs at level 1 with the class "element"
    – SQRCAT
    Commented Nov 22, 2011 at 20:54

4 Answers 4

37

I think what you want to use is the not selector. Like this..

$(".container").not(".container .container")

Alternately, you could use the children selector, to get the children from one level deep. Which would exlclude the nested divs.

To be a little more explicit, I think you'll want to use the not selector after you use the 'find'. Like this:

$(".container").find(".element").not($(".container .container .element"))

You can pass a function to not, so you could have that function look at the parents of each element match to see if it is nested inside of an element with the same class.

http://jsfiddle.net/QXfs2/6/

removeIfNested = function(index) {
    // this is the corrent DOM element
    var $this = $(this),
        return_value = false;

    $.each($this.attr('class').split(/\s+/), function(index) {
        if ($this.parents("." + this).length > 0) {
            return_value = default_value || true;
        }
    });

    return return_value;
}


$(".container").find(".element").not(removeIfNested);

If you could add a class to the nested container, that would be ideal, then it's just:

$(".container").find(".element").not($(".nested .element"))

Assuming you added the class "nested", to your inner container div.

6
  • That's very good to know! In my particular case children() was more fitting though. But thanks a lot for bringing my attention to not(). In any case children() did the job. Until i come up with a case where multiple levels are to be supported.
    – SQRCAT
    Commented Nov 22, 2011 at 20:56
  • I found that i had cases where the DIVs are nested within the containers again, which is why i had to dump children(). Using not() seems like a good idea, but the problem is: what selector to use with not() to match the parent container (not the children directly) ?
    – SQRCAT
    Commented Nov 22, 2011 at 21:05
  • Thank you for that hint. I tried applying it but failed in doing so. I found that it might be easier if i just applied an additional CSS class to all descendant containers, so that i could just exclude them easily. But now i don't seem to be finding out what selector to use in order to select all .container DIVs by using .find() and to exclude all elements that are children of an element with a specific css class. - you were faster. Let me try to apply your latest solution.
    – SQRCAT
    Commented Nov 22, 2011 at 21:22
  • This is it. It worked once i applied your final suggestion and added a > between the parent and the child class names within the not() statement. .not($('.canHaveChildren > .element')) - Thank you! You saved my day.
    – SQRCAT
    Commented Nov 22, 2011 at 21:40
  • Applying the .not($(".nested .element")) after the find syntax helped resolve my need to filter after a find all: $(".container").find("*").not($(".element")) Commented Sep 23, 2014 at 23:42
2

For your specific example this would work -

$("body > div.container > .element")

That will only get the top level element divs. If your element collection was in a different structure you could substitue body with the collection's container id.

Demo - http://jsfiddle.net/QAP37/

1
  • I can't apply this solution as even though the example described above is simplified, the actual situation is a bit more complicated. But thank you.
    – SQRCAT
    Commented Nov 22, 2011 at 21:06
0

You can use jquery selector like this:

find('*:not(.container .container *)')
1
  • 1
    From : api.jquery.com/all-selector .... Caution: The all, or universal, selector is extremely slow, except when used by itself. Just so you know...
    – Marcky
    Commented Nov 30, 2015 at 3:24
0

I found the following slightly more succinct and general than the selected answer. It works with arbitrarily deeply nested trees:

function getNonNestedElements(container, elementSelector, containerSelector) {
  return container.find(elementSelector).not(function(index) {
    var nearest = $(this).closest(containerSelector);
    return nearest[0] !== container[0];
  });
}

where:

  • container is the jQuery object for the root "container" div
  • elementSelector is the jQuery selector for the element, .element in this case
  • containerSelector is the jQuery selector for the container, .container in this case

So this finds all the elements beneath the initial container, then for each element checks to see if its nearest container is the initial container or some other nested container. If its nearest container is a nested container, it throws it out, so you are just left with descendants which are not inside another container.

Very handy for things like repeating multi-element, nested form fields.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.