jQuery 选择器基于 child
jQuery selector based on child
我如何在下面的 html 中,select 所有距离最近的 child 不是跨度的 div?
<div>test</div> //should be selected
<div>test2</div> //should be selected
<div><span>test2<span/></div> //should not be selected
您可以使用伪 class 选择器,例如 :has()
and :not()
。
$("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>
我如何在下面的 html 中,select 所有距离最近的 child 不是跨度的 div?
<div>test</div> //should be selected
<div>test2</div> //should be selected
<div><span>test2<span/></div> //should not be selected
您可以使用伪 class 选择器,例如 :has()
and :not()
。
$("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>