Kev O. Kev O. - 2 months ago 11
jQuery Question

Nested Jquery Selectors current element within a Loop

I have the following Problem: I want to select all children + grandchildren of the current element.

Sample HTML

<html>
<head>
<title>Sample</title>
</head>
<body>
<div class="a">
<div class="b"></div>
</div>
<div class="a">
<div class="b"></div>
</div>
</body>
</html>


My JS Loop goes through every div class A.
I want to select B in within this Loop and only the B of the current div class A.

$(".a").each(function(){
// SELECT div class B here and only the B of the current A
});


Why isn't this working?

$(".a").each(function(){
$(this).contents().filter('.b').each(function(){
console.log("Test");
});
});

Answer

Your implementation didn't worked as the method .filter() matches element at same level. You need to use .find()/.children() since .b is descendant of .a.

$(".a").each(function() {
    $(this).find('.b').each(function() {
        console.log("Test");
    });
});

OR, You can directly use Descendant Selector (“ancestor descendant”)

$(".a .b").each(function() {
    console.log("Test");
});
Comments