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
To check if a div element contains specific text:Use the includes() method to check if the specific text is contained in the div . If it is, the includes() method returns true , otherwise false is returned.
This method can be used on this element to test if it is empty by using “:empty” selector. The “:empty” selector is used to select all the elements that have no children. It will return true if the element is empty, otherwise, return false.
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With