如果内部div具有某个类,如何使用javascript隐藏父div [英] How to hide a parent div if an inner div has a certain class, with javascript

查看:98
本文介绍了如果内部div具有某个类,如何使用javascript隐藏父div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,说我有很多div.有些div的孩子有一个班级,其他div的孩子有不同班级.

Ok so say I have many divs. Some of the divs, the children have one class, other divs the children have a different class.

我只想隐藏有一个具有特定班级孩子的div.

I want to hide only the divs which have a child with a certain class.

例如,

<div class="mainDiv">
    <div class="kulkul">
        <div class="childA">
        </div>
    </div>
</div>

<div class="mainDiv">
    <div class="lalala">
        <div class="childB">
        </div>
    </div>
</div>

<div class="mainDiv">
    <div class="kulkul">
        <div class="childA">
        </div>
    </div>
</div>

<div class="mainDiv">
    <div class="lalala">
        <div class="childA">
        </div>
    </div>
</div>

<div class="mainDiv">
    <div class="kulkul">
        <div class="childB">
        </div>
    </div>
</div>

<div class="mainDiv">
    <div class="lalala">
        <div class="childA">
        </div>
    </div>
</div>

现在在上面,假设我只想隐藏具有子类

Now above, let's say that I only want to hide the parent divs which have a child div with the class .childB

就我所知,CSS还是无法做到这一点(无论如何CSS3),因为CSS不允许您设置父div的样式,只能是子div的样式.父.mainDiv div(我要隐藏的div)完全相同.

This can't be done with CSS as far as I know (CSS3 anyway), because CSS doesn't allow you to style the parent div, only a child div. And the parent .mainDiv divs (the ones I want to hide) are all exactly the same.

这样就剩下了javascript.

So that leaves javascript.

使用上面的示例,如何隐藏所有包含.childB类的子div的所有.mainDiv div?

Using the example above, how can I hide all the .mainDiv divs which contain a child div with the class .childB?

推荐答案

基于其直接后代的隐藏父元素

HIDING PARENT ELEMENT based on its direct descendant

//Update the **sample-element-to-hide** with whatever you wanted to use as a child class with the parent element you wanted to hide e.g., 'childB'
var elementToHideList = document.getElementsByClassName("sample-element-to-hide");
for (var i = elementToHideList.length; i--;)
    elementToHideList[i].parentNode.style.display = "none";

根据其子元素隐藏父元素.

HIDING PARENT ELEMENT based on its child element.

//Solution for the OP
//Update the **childB** with whatever you wanted to use as a child class with the parent element you wanted to hide.
//Note that this would only works if the parent element has a **className** mainDiv. You can change mainDiv with your own parent className.

$('.classB').closest('.mainDiv').hide();

这篇关于如果内部div具有某个类,如何使用javascript隐藏父div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆