如果内部div具有某个类,使用javascript,如何隐藏父div

前端之家收集整理的这篇文章主要介绍了如果内部div具有某个类,使用javascript,如何隐藏父div前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
好的,我说我有很多div.一些div,孩子们有一个班级,其他孩子们有不同的班级.

我想只隐藏有一个特定类的孩子的div.

例如,

<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>

现在上面,假设我只想隐藏具有类.childB的子div的父div

据我所知(CSS3无论如何),这不能用CSS完成,因为CSS不允许你设置父div的样式,只允许子div.父母.mainDiv divs(我想隐藏的那些)都完全一样.

这样就留下了javascript.

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

解决方法

根据其直系后裔隐藏父母元素
//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";

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

//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();
原文链接:https://www.f2er.com/css/215490.html

猜你在找的CSS相关文章