I have a code like this:
<div class='parent one'>
<div class='yes'></div>
<div class='yes'></div>
<div class='yes'></div>
</div>
<div class='parent two'>
<div></div>
<div></div>
<div></div>
</div>
<div class='parent three'>
<div></div>
<div></div>
<div class='yes'></div>
</div>
How do I remove .parent.two
because it doesn't have any child with .yes
? What I've tried so far and it didn't work:
$('.parent div:not(.yes)').remove();
You can use :not
with :has
:
$(() => $('.parent:not(:has(.yes))').remove())
.parent{ background: orange; height: 100px; width: 100px; margin: 10px; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='parent one'>
<div class='yes'>Child of one</div>
<div class='yes'>Child of one</div>
<div class='yes'>Child of one</div>
</div>
<div class='parent two'>
<div>Child of two</div>
<div>Child of two</div>
<div>Child of two</div>
</div>
<div class='parent three'>
<div>Child of three</div>
<div>Child of three</div>
<div class='yes'>Child of three</div>
</div>
You could create a selector as a combination of :not
and :has
and then use remove
method. So this will select all elements with .parent
class that do not have child element with .yes
class.
$('.parent:not(:has(.yes))')
$('.parent:not(:has(.yes))').remove()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='parent one'>
<div class='yes'>one</div>
<div class='yes'></div>
<div class='yes'></div>
</div>
<div class='parent two'>
<div>two</div>
<div></div>
<div></div>
</div>
<div class='parent three'>
<div>three</div>
<div></div>
<div class='yes'></div>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With