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?
Phrasing content is the text of the document, as well as elements that mark up that text at the intra-paragraph level. Runs of phrasing content form paragraphs. That doesn't include div elements, which can only be used where flow content is expected. Therefore, p elements can't contain div elements.
In jQuery, you can use the . length property to check if an element exists. if the element exists, the length property will return the total number of the matched elements. To check if an element which has an id of “div1” exists.
In the first formulation listed above, jQuery() — which can also be written as $() — searches through the DOM for any elements that match the provided selector and creates a new jQuery object that references these elements: 1. $( "div.
$("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
}
});
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With