Select 具有子元素但没有特定 class 的元素列表
Select list of element having a child element without a specific class
<div class="wrapper">
<div class="A B">
<span class="C">needed</span>
</div>
<div class="A B">
<span class="D">not needed</span>
</div>
<div class="A B">
<span class="E">needed</span>
</div>
</div>
我需要所有 div 元素,这些元素没有 class "D" 的子跨度。此操作是否有 jQuery 选择器?
您可以使用 .filter()
:
var divs = $('.A.B').filter(function(){
return $(this).children('span.D').length === 0;
});
console.log(divs.text());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
<div class="A B">
<span class="C">needed</span>
</div>
<div class="A B">
<span class="D">not needed</span>
</div>
<div class="A B">
<span class="E">needed</span>
</div>
</div>
你可以结合使用:has()
and :not()
pseudo-class selectors. Where :has()
can be used for checking the selected element contains any certain element and then filter out them using :not()
selector. Although filter()
方法可以像@Jai[=一样使用34=]回答。
$('.A.B:not(:has(>.D))').css('color', 'red')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
<div class="A B">
<span class="C">needed</span>
</div>
<div class="A B">
<span class="D">not needed</span>
</div>
<div class="A B">
<span class="E">needed</span>
</div>
</div>
仅供参考: 其中 >
(children selector) 用于检查直接子节点,否则它可能会检查嵌套,因此如果没有问题,您可以避免。
<div class="wrapper">
<div class="A B">
<span class="C">needed</span>
</div>
<div class="A B">
<span class="D">not needed</span>
</div>
<div class="A B">
<span class="E">needed</span>
</div>
</div>
我需要所有 div 元素,这些元素没有 class "D" 的子跨度。此操作是否有 jQuery 选择器?
您可以使用 .filter()
:
var divs = $('.A.B').filter(function(){
return $(this).children('span.D').length === 0;
});
console.log(divs.text());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
<div class="A B">
<span class="C">needed</span>
</div>
<div class="A B">
<span class="D">not needed</span>
</div>
<div class="A B">
<span class="E">needed</span>
</div>
</div>
你可以结合使用:has()
and :not()
pseudo-class selectors. Where :has()
can be used for checking the selected element contains any certain element and then filter out them using :not()
selector. Although filter()
方法可以像@Jai[=一样使用34=]回答。
$('.A.B:not(:has(>.D))').css('color', 'red')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
<div class="A B">
<span class="C">needed</span>
</div>
<div class="A B">
<span class="D">not needed</span>
</div>
<div class="A B">
<span class="E">needed</span>
</div>
</div>
仅供参考: 其中 >
(children selector) 用于检查直接子节点,否则它可能会检查嵌套,因此如果没有问题,您可以避免。