如何使用jQuery选择不是特定元素的子元素?

时间:2018-12-14 16:19:11

标签: javascript jquery html jquery-selectors

如何仅选择没有span作为父母的div.option

<div class="option">
    <span>Content goes here</span>
</div>
<span>Content goes here</span>
<span>Content goes here</span>
<div class="option">
    <span>Content goes here</span>
</div>

1 个答案:

答案 0 :(得分:2)

您需要选择所有span,并使用:not()排除属于.option子级的跨度

$("span:not(div.option > span)").css("color", "red");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="option">
    <span>Content goes here</span>
</div>
<span>Content goes here</span>
<span>Content goes here</span>
<div class="option">
    <span>Content goes here</span>
</div>