Jquery selection of children not invested in a child

I have some problems with jQuery selector.

Let's say I have the following html, where (...) denotes the number of html undefined tags.

 (...) <div class="container"> (...) <div class="subContainer"> (...) <div class="container"> (...) <div class="subContainer"/> (...) </div> (...) </div> (...) </div> (...) 

Let's say that I have a javascript variable called container that points to the first div (with the class container). I want a jquery that selects the first subcontainer, but not nested. If I use $(".subContainer", container); I will get both of them.

I tried using

 $(".subContainer:not(.container .subContainer)", container); 

but this returns an empty set. Any solution?

Thanks.

+8
javascript jquery html jquery-selectors
source share
4 answers

JQuery- based : get all the elements of a class that are not decomment for an element with the same class name? I developed the following solution. Thanks to everyone.

 $.fn.findButNotNested = function(selector, notInSelector) { var origElement = $(this); return origElement.find(selector).filter(function() { return origElement[0] == $(this).closest(notInSelector)[0]; }); }; 
+7
source share

You can use the direct child selector:

 $("> .subContainer", container); 

If container is a jQuery object related to a top-level .container , you can also use the children method:

 container.children('.subContainer'); 

Or find and first :

 container.find('.subContainer').first(); 
+7
source share

To get the first subcontainer, you can use

 $('.subContainer')[0] 
0
source share

This seems to work for my own purposes ...

 $('.item').filter(function() { return $(this).parents('.item').length == 0; }); 

This returns only the #outer div.

 <div class="item" id="outer"> <div class="item" id="inner"></div> </div> 
0
source share

All Articles