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?
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?
Give your div an ID, 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 grab any p
inside any div
. This is basically what @karim79 has.
$("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
}
});
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
}
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) ...
I need to add a class to every div containing a <li>
-Tag. What I have now:
$("div #myDiv").each(function () {
if ($(this).find("li").length == 0) {
$(this).addClass("hasNoLi");
}
});
}
Line 3 doesn't seem to work. Any suggestions?