Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - how to select elements not containing specific elelments

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.

like image 946
Jan Krakora Avatar asked Dec 12 '25 09:12

Jan Krakora


1 Answers

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>
like image 130
Milind Anantwar Avatar answered Dec 15 '25 04:12

Milind Anantwar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!