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.

Brandon
  • 247
  • 2
  • 3
  • 5

3 Answers3

23

This should do:

if ($("#gallery > div.show").length > 0)
Xion
  • 22,400
  • 10
  • 55
  • 79
9

if you wish to keep jQuery chaining capability, use:

$("#gallery").has(".show").css("background","red"); //For example..
Valéry
  • 344
  • 2
  • 6
7

How about:

$("#gallery div").each(function (index, element) {
if($(element).hasClass("show")) {
//do your stuff
}
});
Thomas Shields
  • 8,874
  • 5
  • 42
  • 77