0

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!

Gerard
  • 15,418
  • 5
  • 30
  • 52
JonSnow
  • 573
  • 14
  • 48
  • How do you get this empty element? tehres no parent selector in css. I think best solution is check before if the element is empty or not – Sfili_81 Nov 23 '22 at 16:29
  • The empty element is provided by a partner company. They are leaving the whole node in the code even though it's not neccessary. And as every list element has a css declaration I wanted to identify the empty ones to hide them at all. The solution provided from @Gerard is just perfect! – JonSnow Nov 24 '22 at 09:53

1 Answers1

4

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>
Gerard
  • 15,418
  • 5
  • 30
  • 52