0

I would like to use CSS to hide a div if it does not contain any li descendents.

Given this:

<div>
   I should be visible (red)
   <ul>
     <li>one</li>
   </ul>
</div>

<div>
  I should be hidden (blue)
  <ul></ul>
</div>

What CSS can I use to select the second div and apply display:none (or border:1px solid blue for this demo)?

Here is a fiddle: https://jsfiddle.net/7yab2z27/

Daniel
  • 3,021
  • 5
  • 35
  • 50

2 Answers2

0

You might consider using JS in this situation, See my code might helps. Dont forget to include

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>

I found your answer here: jQuery to hide a DIV if it has no unordered list items

$(document).ready(function() {

  $('#seconddiv').hide();
  $('#seconddiv').has('ul').show();
});
#seconddiv {
  display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<div id="seconddiv">
  You cant see me I dont have unordered list lol!
  <ul>
    <li></li>
  </ul>
</div>
Community
  • 1
  • 1
erp
  • 11
  • 4
0

The thing with CSS is that you cannot make changes to parent/ancestor based on the presence or state of a descendant. The opposite is true.

In this situation, you would want to use JS and apply the styles as necessary based on condition.

Assuming you were using jQuery, you could do something like following.

var allDivs = $("div");
allDivs.each(function(index,eachDiv){
    if( $(eachDiv).find("li").length === 0 ){
        $(eachDiv).hide();
    }
});
Praveen Puglia
  • 5,577
  • 5
  • 34
  • 68