Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test if a div doesn't have an element

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

like image 669
SparrwHawk Avatar asked Feb 09 '12 15:02

SparrwHawk


People also ask

How do I check if a div contains an element?

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.

How do you test if an element is empty?

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.


Video Answer


1 Answers

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');
like image 66
Didier Ghys Avatar answered Sep 22 '22 10:09

Didier Ghys