agvr3 agvr3 - 4 months ago 17
jQuery Question

How to hide a parent div if an inner div has a certain class, with javascript

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

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

For example,

<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


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.

So that leaves javascript.

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

Answer

A faster way to do this was doing it with pure javascript.

Assuming you want to hide a PARENT ELEMENT with a DIRECT DESCENDANT/CHILD ELEMENT with a classname 'sample-element-to-hide'

//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");
/*
 * BACKUP for direct descendent 
for (var i = elementToHideList.length; i--;)
    elementToHideList[i].parentNode.style.display = "none";
*/

//Solution with pure jQuery
$('.classB').closest('.mainDiv').hide();
Comments