jQuery 如何检测父元素中的任何子元素是否具有某个类?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5844886/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to detect if any child elements within a parent element has a certain class?
提问by Brandon
I'm trying to detect if any of the sub-divs within the parent "gallery" div have a class of "show".
我试图检测父“画廊”div 中的任何子 div 是否具有“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.
它不必是 if/else 格式。能够以 jQuery 链接的方式做到这一点会更好。
回答by Xion
This should do:
这应该做:
if ($("#gallery > div.show").length > 0)
回答by Valéry
if you wish to keep jQuery chaining capability, use:
如果您希望保留 jQuery 链接功能,请使用:
$("#gallery").has(".show").css("background","red"); //For example..
回答by Thomas Shields
How about:
怎么样:
$("#gallery div").each(function (index, element) {
if($(element).hasClass("show")) {
//do your stuff
}
});