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!

2
  • 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, 2022 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, 2022 at 9:53

1 Answer 1

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>

1
  • This is awesome and absolutely works for my problem - thank you so much!
    – JonSnow
    Nov 24, 2022 at 7:25

Not the answer you're looking for? Browse other questions tagged or ask your own question.