Reputation: 5025
<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
Reputation: 60516
$(':not(.test:has(.example))').css('color', 'red');
Upvotes: 3
Reputation: 1
if (!$('#yourDiv').children().hasClass("className")) {
//i.e. yourDivID' has no any children whose class name =>'className'
}
Upvotes: -1
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
Reputation: 42109
$('.test:not(:has(.example))')
-or-
$('.test').not(':has(.example)')
Upvotes: 49
Reputation: 4070
$('.test').each(function() {
if(!$(this).children().hasClass("example")){
//your code
}
});
Maybe like this? I haven't tested this...
Upvotes: 1
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
Reputation: 11613
jQuery contains()
:
jQuery.contains(document.documentElement, document.body); // true
jQuery.contains(document.body, document.documentElement); // false
Upvotes: 2
Reputation: 881
You could use the method children with ".example" and test if it is empty
Upvotes: 1