Check if div element has element

I am trying to do something if the div contains a specific element but does not seem to be able to trigger a condition. Here is 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 just targets absolutely everything. Here is a live violin - http://jsbin.com/igoyuk/edit#javascript,html,live

+6
source share
4 answers

Remember that . has () returns jQuery , not boolean!

.has (selector) Returns: jQuery
Description. Reduce the set of matched elements to those who have a child that matches the selector element or DOM element.

Doing if(!$(this).has('p')) always true, since jQuery always returns a set, even if it is empty!

.has() basically filters the set on which it is called, so you just need to do:

 $('.test').has('p').addClass('red'); 
+11
source
 if (!($(this).find('p').length > 0)) { $(this).addClass('red'); } 
+3
source

Consider the following:

 $("div.test:has(p)").addClass("red"); 

This queries your DOM for the <div> elements, selecting only those that have a test class, and then looks to see if it has a <p/> element. Its bit is shorter = fewer bytes passing through the wire.

+2
source

You can use the following condition to check for the absence of an element type:

 if($('p', $(this)).length == 0) 

Since $('p', $(this)) will return all p elements inside the current element.

0
source

Source: https://habr.com/ru/post/908051/


All Articles