Jan Krakora
Jan Krakora

Reputation: 2610

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.

Upvotes: 3

Views: 645

Answers (1)

Milind Anantwar
Milind Anantwar

Reputation: 82251

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>

Upvotes: 2

Related Questions