Use jQuery to get descendants of an element that are not children of a container with a certain CSS class

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.


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/