我有以下问题:我想选择当前元素的所有子项+孙子。
示例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 :(得分:4)
由于方法.filter()
与同一级别的元素匹配,因此您的实现无效。您需要使用.find()
/ .children()
,因为.b
是.a
的后代。
$(".a").each(function() {
$(this).find('.b').each(function() {
console.log("Test");
});
});
或,您可以直接使用Descendant Selector (“ancestor descendant”)
$(".a .b").each(function() {
console.log("Test");
});
答案 1 :(得分:0)
您需要在A:
中找到“B” $(".a").each(function(){
$(this).find('.b').each(function(){
console.log("Test");
});
});