2016-09-06 6 views
1

次の問題があります。問題:現在の要素のすべての子要素と孫要素を選択したい。ループ内の現在の要素をネストしたJqueryセレクタ

サンプル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> 

私のJSループは、すべてのdivクラスA. を通過、私はこのループ内でBを選択すると、現在のdivクラスAの唯一のB

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

これはなぜ機能しないのですか?

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

https://api.jquery.com// nearest/ –

+0

'$( '.a .b')。それぞれ(function(){$ this} .closest( '.b'))addClass( 'selected')。end()。addClass( 'selected' );}); ' – Tushar

答えて

4

.filter()のメソッドが同じレベルの要素と一致するため、実装が機能しませんでした。 .b.aの子孫であるため、.find()/.children()を使用する必要があります。

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

OR、あなたが直接あなたがAの中に "B" を見つける必要があるだろうDescendant Selector (“ancestor descendant”)

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

を使用することができます。

$(".a").each(function(){ 
    $(this).find('.b').each(function(){ 
    console.log("Test"); 
}); 
}); 
関連する問題