jQuery 如何选择父级未指定类的元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6784741/
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 select an element which parent is not specified class?
提问by Naoise Golden
I want to hide an element if its parent does not have a certain class:
如果它的父元素没有某个类,我想隐藏它:
HTML
HTML
<li class="current_page_parent">
<a href="parent.html">Parent</a>
<ul class="children">
<li>foo</li>
<li>bar</li>
</ul>
</li>
jQuery
jQuery
jQuery("ul.children").hide();
Currently always hides <ul class="children">
regardless of class. I would like to close it only if parent is :not
an <li class="current_page_parent">
.
目前总是隐藏,<ul class="children">
无论等级如何。我想只有关闭它,如果父母是:not
一个<li class="current_page_parent">
。
I've tried:
我试过了:
jQuery("ul.children:not(:parent.current_page_ancestor)").hide();
with no luck.
没有运气。
回答by hlcs
回答by Chandu
Try this:
尝试这个:
jQuery("li:not(.current_page_parent) ul.children").hide();
回答by sth
You probably want to firstfilter out the ul
elements with a "bad" parent and thenselect all the children:
您可能希望首先过滤掉ul
具有“坏”父级的元素,然后选择所有子级:
jQuery("ul:not(:parent.current_page_ancestor).children")
回答by user1489742
$('ul').filter(function() {
return $(this).parent('.current_page_parent').length === 0
}).hide();