Reputation: 2698
I have some problems with a jQuery selector.
Let's say I have the following html where (...)
stands for an undefined number of html tags.
(...)
<div class="container">
(...)
<div class="subContainer">
(...)
<div class="container">
(...)
<div class="subContainer"/>
(...)
</div>
(...)
</div>
(...)
</div>
(...)
Let say that I have a javascript variable called container
that points to the first div (with class container).
I want a jquery that selects the first subcontainer but not the nested one.
If I use$(".subContainer", container);
I'll get both of them.
I've tried using
$(".subContainer:not(.container .subContainer)", container);
but this returns an empty set. Any solution?
Thanks.
Upvotes: 9
Views: 7415
Reputation: 4435
This seems to work for my own uses...
$('.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>
Upvotes: 0
Reputation: 2698
Based on Jquery: Get all elements of a class that are not decendents of an element with the same class name? I've developed the following solution. Thanks to all.
$.fn.findButNotNested = function(selector, notInSelector) {
var origElement = $(this);
return origElement.find(selector).filter(function() {
return origElement[0] == $(this).closest(notInSelector)[0];
});
};
Upvotes: 8
Reputation: 144659
You can use direct child
selector:
$("> .subContainer", container);
If container
is a jQuery object that refers to top-level .container
element you can also use children
method:
container.children('.subContainer');
Or find
and first
methods:
container.find('.subContainer').first();
Upvotes: 8
Reputation: 724
To get the first subContainer you can use
$('.subContainer')[0]
Upvotes: 0