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.
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.
Share Improve this question edited Dec 28, 2012 at 15:58 Samuel Caillerie 8,2752 gold badges29 silver badges34 bronze badges asked Dec 28, 2012 at 15:51 MateuMateu 2,6986 gold badges38 silver badges56 bronze badges 3 |4 Answers
Reset to default 8You 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();
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];
});
};
To get the first subContainer you can use
$('.subContainer')[0]
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>
$(".subContainer:first", container)
$(".subContainer", container).first()
might work. – rlemon Commented Dec 28, 2012 at 15:56