如何在下面的html中选择最接近的孩子不是跨度的所有div?
<div>test</div> //should be selected
<div>test2</div> //should be selected
<div><span>test2<span/></div> //should not be selected
答案 0 :(得分:1)
$("div:not(:has(span))").css("color","red");
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<div>test</div>
<div>test2</div>
<div><span>test2</span></div>
filter()
方法。
$("div").filter(function() {
// get all children nodes and check first node is span(assuming there isn't any comment node)
return !$(this).contents().first().is('span');
}).css("color", "red");
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<div>test</div>
<div>test2</div>
<div><span>test2</span></div>
<div>test3<span>test2</span></div>
<div> <span>test2</span></div>
答案 1 :(得分:0)
您可以使用jquery .not()
和.has()
方法。
$("div").not($("div").has("span")).css("color","red");
<div>test</div>
<div>test2</div>
<div><span>test2<span/></div>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>