Css hide div if div has no child with class

Is it possible to hide a div with css if the div does not have a child div with a specific class name?

<div class="parent"> This div must be hidden </div> <div class="parent"> This div must be visible <div class="child"> child div </div> </div> 

If this is not possible with CSS, perhaps with javascript or jQuery?

+4
source share
2 answers

I don't think this is possible with CSS only, but it is definitely possible with Javascript.

You need to - find all divs with class parent
- find all those who have a child div with class child
- if there is no such child, set style.display = none

Now that is pure javascript , it can be a little more complicated. You can use getElementsByClassName from this question and then apply the above logic:

 //getElementsByClassName from @CMS answer to the linked question var parentDivs = getElementsByClassName(document, "parent"); for(var i=0; i<parentDivs.length; i++) { var children = getElementsByClassName(parentDivs[i], "child"); if(!children || children.length == 0) { parentDivs[i].style.display = "none"; } } 

With jQuery, this is much simpler:

 $(".parent").each(function() { if($(this).children(".child").length == 0) { $(this).hide(); } }); 

Live Example: http://jsfiddle.net/nivas/JWa9r/

+6
source

With CSS3 you can use: an empty selector. This method is widely supported by all modern browsers and is much faster than the javascript alternative.

+12
source

All Articles