JQuery returns true or false if the div contains a <p> tag
We'll see:
<div><p>this div contains ap tag</p></div> <div>this one is not</div> How to assign a variable with a boolean value (true or false) if the div contains a specific tag of type p in the above example?
$("div:has(p)").addClass("has-paragraph"); will add a class to all divs containing p children. If paragraphs are not direct children, this will not take them away.
Note :
$("div p").addClass("has-paragraph"); Add a class to the paragraph, not a div. You can fix it:
$("div p").parents("div").addClass("has-paragraph"); but it will catch several div ancestors. You can do it:
$("div p").parents("div:first").addClass("has-paragraph"); to fix it.
Or more programmatically:
$("div").each(function() { if ($(this).find("p").length > 0) { // do stuff } }); Give your div ID and then:
if($('#myDiv p').length) { alert('I have a paragraph'); } var result = ($('div p').size() > 0); or
var result = ($('div p').length > 0); This will capture any p inside any div . This is basically what @ karim79 has.
That would be my bet:
$("div").each(function(){ if ($(this).children('p').length>0){ // do stuff, assign boolean if you want } }); I suggested that you are looking for direct children. If not, use
if ($(':has(p)',this).length>0) ... Not sure how you want to store your information, but the following code will collect all the div tags containing the p tag.
$("div:has(p)").each( function () { # Store what you need here }); If you have a specific div that you want to test, the following should work based on a "true" value. I am sure that someone can get you true or false value through smart means.
if ( $("#divId:has(p)") ) { # Do what you need here }