Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

jquery

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.

like image 792
Brandon Avatar asked Apr 30 '11 22:04

Brandon


3 Answers

This should do:

if ($("#gallery > div.show").length > 0)
like image 53
Xion Avatar answered Oct 13 '22 13:10

Xion


if you wish to keep jQuery chaining capability, use:

$("#gallery").has(".show").css("background","red"); //For example..
like image 31
Valéry Avatar answered Oct 13 '22 14:10

Valéry


How about:

$("#gallery div").each(function (index, element) {
if($(element).hasClass("show")) {
//do your stuff
}
});
like image 7
Thomas Shields Avatar answered Oct 13 '22 13:10

Thomas Shields