Given this:
<div id="div1">
<div id="div2">
<div id="div200">
<div id="div3" class="b">
</div>
<div id="div300">
<div id="div4" class="b">
<div id="div5">
<div id="div6" class="b">
</div>
</div>
</div>
<div>
<div>
<div>
</div>
I need a way to find the children (deep) of an element that are of class "b" but not those that are nested inside a matched element.
Test cases:
This is what I need:
Case 1:
$("#div1").some_jquery_syntax(".b")
Should return:
div3, div4
Case 2:
$("#div5").some_jquery_syntax(".b")
Should return:
div6
Note that the hard part is that I have have to skip div2 when starting from div1. So I can't just use $("#div1").find("> .b")
.
My attempts:
I tried this:
$("#div1").find(".b")
[<div id="div3" class="b"></div>, <div id="div4" class="b"></div>, <div id="div5" class="b"></div>]
Not good: I don't want div5 because it is nested inside div4.
I tried this:
$("#div0").find(".b").not(".b .b")
[<div id="div3" class="b"></div>, <div id="div4" class="b"></div>]
Which is ok when starting with div0, but it does not work stating from div4:
$("#div5").find(".b").not(".b .b")
[]
children(selector) – In jquery you can achieve this task by using the method named . children(). It takes the selector as a parameter and changes the children element with the specified name.
The 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.
The ("parent > child") selector selects all elements that are a direct child of the specified element.
Select the parent element whose child element is going to be selected. Use . querySelector() method on parent. Use the className of the child to select that particular child.
Find the immediate grand-children:
$("#div1").children().children(".b");
Fiddle: http://jsfiddle.net/jonathansampson/Dy6GJ/
If you don't know how deep to go, but want all .b
not within a .b
, use a filter while respecting parent limitations. You could use the .parentsUntil
method:
var parent = "#div1";
$(".b", parent).filter(function(){
return !$(this).parentsUntil(parent, ".b").length;
}).css("border", "1px solid red");
Fiddle: http://jsfiddle.net/jonathansampson/Dy6GJ/3/
General (when only class can be guaranteed):
$("#div1").find(".b:not(.b .b)")
As described (likely faster than general, though not tested):
$("#div1").find("div.b:not(div.b div.b)")
"All .b which are not descendants of .b"
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