UserIsCorrupt
UserIsCorrupt

Reputation: 5025

How can I select an element which does not contain a certain child element?

<div class="test">
 <div class="example"></div>
</div>

<div class="test">
</div>

How can I apply jQuery to an element with the class test only if it doesn't contain a child element with the class example?

Upvotes: 26

Views: 26665

Answers (8)

Andreas Wong
Andreas Wong

Reputation: 60516

$(':not(.test:has(.example))').css('color', 'red');​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

http://jsfiddle.net/9fkz7y1g/

Upvotes: 3

Shekhar Kadam
Shekhar Kadam

Reputation: 1

if (!$('#yourDiv').children().hasClass("className")) {
    //i.e. yourDivID' has no any children whose class name =>'className'
}

Upvotes: -1

jfriend00
jfriend00

Reputation: 707326

This problem seems ready-made for the filter function where you find all the .test objects and then when filtering retain only the ones that don't have .example in them:

$(".test").filter(function() {
    return($(this).find(".example").length == 0);
});

Upvotes: 2

vol7ron
vol7ron

Reputation: 42109

$('.test:not(:has(.example))')

-or-

$('.test').not(':has(.example)')

Upvotes: 49

hjuster
hjuster

Reputation: 4070

 $('.test').each(function() {
    if(!$(this).children().hasClass("example")){
       //your code
    }
}); 

Maybe like this? I haven't tested this...

Upvotes: 1

Jon
Jon

Reputation: 437376

Possibly

$('.test').filter(function() { return !$(this).children('.example').length; });

This filters out any elements that have any child that matches .example. If you want to filter based on descendants (not just children) that you can substitute .find for .children.

Upvotes: 5

Marc
Marc

Reputation: 11613

jQuery contains():

jQuery.contains(document.documentElement, document.body); // true
jQuery.contains(document.body, document.documentElement); // false

Upvotes: 2

Andr&#233;s
Andr&#233;s

Reputation: 881

You could use the method children with ".example" and test if it is empty

Upvotes: 1

Related Questions