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
Be aware that .has() returns jQuery, not a boolean !
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: