tags:

views:

1201

answers:

6

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?

+3  A: 

Give your div an ID, then:

if($('#myDiv p').length) {
    alert('I have a paragraph');
}
karim79
both work it's just that Daniel's is exacty what i was looking for :)
I just wondering what the difference between this and @Daniels? @Karim gave the first correct answer, but you have accepted the late one. I think it's not fair.
Artem Barger
there's no difference really. Daniel said cletus answer was the most efficient way to do it and i marked this as the correct one :)
+2  A: 
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.

Daniel A. White
Although this is correct, I think cletus's answer deserves to be marked as the answer, because it uses jQuery's built-in has() selector, which should (in theory) be more efficient
Philippe Leybaert
fair enough :) why not. Kudos for playing fair
+7  A: 
$("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
  }
});
cletus
A: 

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
}
James van Dyke
+1  A: 

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) ...
subtenante
A: 

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?

guz