I'm trying to select elements that does not contain another elements.
Let's say I have a structure like this
<div class="wrap">
<div class="first"></div>
<div class="second">
<div class="content">
<div class="poison-pill"></div>
</div>
</div>
</div>
Where .poison-pill can be anywhere. I need to select a div with either class first or second but only if it doesn't contain an element with class poison-pill.
Is there a more elegant way than using a function in filter?
$('.first, .second').filter(function(index, element) {
return $(element).has('.poison-pill').length === 0;
});
I can think of using the not function or :not selector or something.
You can use .not() with :has selector:
$('.first, .second').not(':has(.poison-pill)')
$(function(){
$('.first, .second').not(':has(.poison-pill)').css('background','green');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrap">
<div class="first">a</div>
<div class="second">
<div class="content">
<div class="poison-pill">b</div>
</div>
</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