Tutorial :jQuery return true or false if a div contains a

tag



Question:

Let's see:

<div><p>this div contains a p tag</p></div>  <div>this one is not</div>  

How do i assign a variable with a boolean value (true or false) if a div contains a specific tag like p in the above example?


Solution:1

$("div:has(p)").addClass("has-paragraph");  

will add a class to all divs that contain p children. If the paragraphs aren't direct children, this won't pick them up.

Note: doing this:

$("div p").addClass("has-paragraph");  

will add the class to the paragraph not the div. You can fix that by doing this:

$("div p").parents("div").addClass("has-paragraph");  

but this will catch multiple div ancestors. You could do this:

$("div p").parents("div:first").addClass("has-paragraph");  

to fix that.

Or more programmatically:

$("div").each(function() {    if ($(this).find("p").length > 0) {      // do stuff    }  });  


Solution:2

Give your div an ID, then:

if($('#myDiv p').length) {      alert('I have a paragraph');  }  


Solution:3

var result = ($('div p').size() > 0);  

or

var result = ($('div p').length > 0);  

This will grab any p inside any div. This is basically what @karim79 has.


Solution:4

This would be my bet :

$("div").each(function(){      if ($(this).children('p').length>0){          // do stuff, assign boolean if you want      }  });  

I assumed you are looking for direct children. If not, use

if ($(':has(p)',this).length>0) ...  


Solution:5

Not sure how you want to store your information, but the following code will gather all div tags which contain a p tag.

$("div:has(p)").each( function () {      # Store what you need here  });  

If you have a specific div you want to test the following should work based on a "truthy" value. I'm sure someone can get you exactly a true or false value through some clever means.

if ( $("#divId:has(p)") ) {      # Do what you need here  }  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »