Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

css hide div if div has no child with class

Tags:

css

Is it possible to hide a div with css if the div has no child div's 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 it's not possible with CSS, maybe with javascript or jQuery?

like image 440
FLY Avatar asked Aug 04 '11 09:08

FLY


People also ask

How do I completely hide a div in CSS?

You can hide an element in CSS using the CSS properties display: none or visibility: hidden . display: none removes the entire element from the page and mat affect the layout of the page. visibility: hidden hides the element while keeping the space the same.

How do I hide div?

We hide the divs by adding a CSS class called hidden to the outer div called . text_container . This will trigger CSS to hide the inner div.

How do you hide a div with kids?

If you want the children to hide, either set them to be visibility: hidden too, or use display: none on the parent element. So, as Kyle pointed out, you can use $('#parent_div'). toggle(); , which will easily apply a display: none to #parent_div .


2 Answers

Since of CSS3 you can use the :empty selector. This method is widely supported by all modern browsers and is much faster than it's javascript alternative.

like image 171
Bosken85 Avatar answered Sep 20 '22 06:09

Bosken85


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

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

Now, with pure javascript this can be a bit complicated. You can use the getElementsByClassName from this question and then apply the above logic:

//getElementsByClassName from @CMS's 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 lot more simple:

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

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

like image 43
Nivas Avatar answered Sep 22 '22 06:09

Nivas