Reputation: 14153
I'm trying to do something if a div contains a certain element, but can't seem to trigger the condition. Here's my best shot.
<div class='test'>
testing123
</div>
<div class='test'>
<p>testing456</p>
</div>
$('.test').each(function(){
if(!$(this).has('p')) {
$(this).addClass('red');
}
});
the script is just targeting absolutely everything. Here is a live fiddle - http://jsbin.com/igoyuk/edit#javascript,html,live
Upvotes: 6
Views: 3564
Reputation: 21
Consider using the following:
$("div.test:has(p)").addClass("red");
This queries your DOM for <div>
elements, selecting only those with the test class and then looks to see if it has a <p/>
element. Its a bit more terse = fewer bytes going over the wire.
Upvotes: 2
Reputation: 30666
Be aware that .has() returns jQuery, not a boolean !
.has( selector ) Returns: jQuery
Description: Reduce the set of matched elements to those that have a descendant that matches the selector or DOM element.
Doing if(!$(this).has('p'))
is always true, as jQuery always returns a set, even if it is empty !
.has()
basically filters the set it is called upon, so you just have to do:
$('.test').has('p').addClass('red');
Upvotes: 11
Reputation: 7489
You could use the following condition to check for the absence of an element type:
if($('p', $(this)).length == 0)
Since $('p', $(this))
will return all of the p
elements inside the current element.
Upvotes: 0