noclist
noclist

Reputation: 1819

How to select element that isn't a child of specific element using jquery?

How can I select only the spans that do NOT have div.option as a parent?

<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>

Upvotes: 2

Views: 59

Answers (1)

Mohammad
Mohammad

Reputation: 21489

You need to select all span and using :not() exclude spans that is child of .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>

Upvotes: 2

Related Questions