0

how to specify CSS for an element without any grandchild elements? e.g.,

<div class="foo">
   <ul></ul>
</div>

<div class="foo">
   <ul><li></li></ul>
</div>

// hide the <div> whose child <ul> is empty, how?
div.foo {
   display: none;
}
eastwater
  • 4,624
  • 9
  • 49
  • 118
  • CSS currently does not support `:has()`, you must use JavaScript as answered [here](https://stackoverflow.com/questions/18189147/selecting-an-element-that-doesnt-have-a-child-with-a-certain-class/53173276), [here](https://stackoverflow.com/questions/49700262/is-it-possible-to-select-elements-that-do-not-have-a-child-of-a-certain-type) – vee Jan 01 '22 at 04:16
  • can XPath be used in CSS? div.foo[count(ul/li)=0] {...} – eastwater Jan 01 '22 at 04:42
  • There are no `count()` in CSS. – vee Jan 01 '22 at 05:16

1 Answers1

2

Hey there is :empty selector in css which allows you to do like this.

Javascript method to get what you asked for

But If you want to hide other things you should use javascript

:has is experimental A simple way of doing this

let text = document.querySelector("div.foo > ul");
if(text.innerHTML == ""){
// set your things
document.querySelector("div.foo").style.display = "none";
// you can delete this thing too but this is just an examplee
}

using :empty selector

If you don't wanna use javascript then this method is also good

Simply use

div > ul:empty{
display:none; // or any styles that you can see
}

For just illustration purpose :

div.foo > ul{
background-color:blue;
height:30px;
}

div.foo > ul:empty{
display:none;
}
<!-- Below is empty ul -->
<div class="foo">
<ul></ul>
</div>
<!-- Below is non empty ul -->
<div class="foo">
<ul>
<li>This is with  text</li>
</ul>
</div>

But be carefull

Empty elements are elements that have nothing in them. It cannot even have a whitespace.

There is something called :blank but it is experimental as far as I know.

prosach
  • 312
  • 2
  • 14