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.
jQuery children() MethodThe children() method returns all direct children of the selected element. The DOM tree: This method only traverse a single level down the DOM tree. To traverse down multiple levels (to return grandchildren or other descendants), use the find() method.
Answer: Use the jQuery find() Method You can use the find() method to get the children of the $(this) selector using jQuery. The jQuery code in the following example will simply select the child <img> element and apply some CSS style on it on click of the parent <div> element.
The ("parent > child") selector selects all elements that are a direct child of the specified element.
jQuery find() Method The find() method returns descendant elements of the selected element, all the way down to the last descendant.
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();
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];
});
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With