好吧,说我有很多div。在某些div中, child 有一个类(class),在其他div中, child 有不同的类(class)。
我只想隐藏有一个类(class)有 child 的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>
现在在上面,假设我只想隐藏具有子div类
.childB
的父div就我所知,CSS还是无法做到这一点(无论如何CSS3),因为CSS不允许您设置父div的样式,只能设置子div的样式。父
.mainDiv
div(我要隐藏的div)完全相同。这样就剩下了javascript。
使用上面的示例,如何隐藏所有包含带有
.mainDiv
类的子div的.childB
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();
关于javascript - 如果内部div具有某个类,如何使用javascript隐藏父div,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38318676/