Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery return true or false if a div contains a <p> tag

Tags:

html

jquery

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?

like image 631
user119210 Avatar asked Jun 08 '09 14:06

user119210


People also ask

Can a P contain a div?

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.

How do you check whether a div is present or not in jQuery?

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.

What is $() in jQuery?

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.


3 Answers

$("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
  }
});
like image 134
cletus Avatar answered Nov 15 '22 07:11

cletus


Give your div an ID, then:

if($('#myDiv p').length) {
    alert('I have a paragraph');
}
like image 25
karim79 Avatar answered Nov 15 '22 08:11

karim79


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.

like image 28
Daniel A. White Avatar answered Nov 15 '22 08:11

Daniel A. White