Alex Rivera | Logout

How to detect if any child elements within a parent element has a certain class?

Asked 2011-04-30T22:00:28.480
16

I'm trying to detect if any of the sub-divs within the parent "gallery" div have a class of "show".

<div id="gallery">

<div class="show"></div>
<div></div>
<div></div>

</div>

if (TEST CONDITION) {
   alert('sub element with the class show found');
} else {
   alert('not found');
}

It doesn't have to be in a if/else format. To be able to do this in a jQuery chainning sort of way would be better.

Edit
Report

2 Answers

23

This should do:

if ($("#gallery > div.show").length > 0)
answered 2011-04-30T22:03:51.183
9

if you wish to keep jQuery chaining capability, use:

$("#gallery").has(".show").css("background","red"); //For example..
answered 2013-02-08T11:28:04.197

Your Answer