CSS: Hide parent if child is :empty?

Issue

I want to hide the parent <li> tag if its child <a> tag is empty. So in the following example I would like to hide the second <li>:

<ul>
  <li>
    <a href="test1.html">Test 1</a>
  </li>
  <li>
    <a></a>
  </li>
  <li>
    <a href="test2.html">Test 2</a>
  </li>
</ul>

I can reach the <a> via li a:empty and that works fine. But how do I get to its parent, the <li> ? Only CSS solutions, please… thanks!

Solution

The only CSS solution is the has() pseudo selector. Unfortunately, it’s not yet supported by Firefox

You may want to consider a polyfill until then.

li:has(a:empty) {
  display: none;
}
<ul>
  <li>
    <a href="test1.html">Test 1</a>
  </li>
  <li>
    <a></a>
  </li>
  <li>
    <a href="test2.html">Test 2</a>
  </li>
</ul>

Answered By – Gerard

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published