简体   繁体   中英

How can I hide parent element of all elements with a given class, but the parent element also has a specific class?

I want to hide all instances of an li element with class parent that have an immediate child div element with class child-1 . Here's a pseudocode example, where the method hideParent() would hide the parent of the selected element(s):

$("li.parent > div.child-1").hideParent();

The following is an example of my HTML, in which the second and third li.parent elements should be hidden.

<li class="parent">
    <div class="child-0"> ... </div>
</li>
<li class="parent">
    <div class="child-1"> ... </div>
</li>
<li class="parent">
    <div class="child-1"> ... </div>
</li>

尝试这个:

$("li.parent > div.child-1").parent().hide();

Select the relevant child elements directly, target their parents (filtered by the relevant selector), then hide them.

$("div.child-1").parent('li.parent').hide();

See:
parent Documentation

Another option is with using filter :

$("li").filter(function () {
    var $this = $(this);
    var isParent = $this.hasClass("parent");
    var childMatchCount = $this.children("div").filter(".child-1").length;
    return isParent && childMatchCount;
}).hide();

DEMO: http://jsfiddle.net/GEhfP/

Although this can be optimized in several ways. But to me, it's more "readable", in a very explicit sense. Using jsperf, the quickest I can get filter to work is with:

$("li.parent").filter(function () {
    return $(this).children("div.child-1").length;
}).hide();

@Joe's answer was the fastest with: $("li.parent > div.child-1").parent()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM