How to select an element which parent is not specified class?

谁都会走 提交于 2019-12-18 18:50:55

问题


I want to hide an element if its parent does not have a certain class:

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("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">.

I've tried:

jQuery("ul.children:not(:parent.current_page_ancestor)").hide();

with no luck.


回答1:


Try this:

jQuery("li:not(.current_page_parent) ul.children").hide();



回答2:


The best way I think:

$(".children").not(".current_page_parent .children").hide();

JSFiddle




回答3:


You probably want to first filter out the ul elements with a "bad" parent and then select all the children:

jQuery("ul:not(:parent.current_page_ancestor).children")



回答4:


$('ul').filter(function() {
    return $(this).parent('.current_page_parent').length === 0
}).hide();


来源:https://stackoverflow.com/questions/6784741/how-to-select-an-element-which-parent-is-not-specified-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!