I’m building a nested drop down navigation for products and I want to automatically hide any categories that are empty.
Unfortunately server side language does not allow efficient way of doing this, so I thought I could output number of products each category has directly, then use jQuery to remove any empty nodes.
I want to target only the li‘s within nav#top_nav:
<nav id="top_nav">
<nav class="nav1">
<ul>
<li data-num-products="0">
<a href="...">AAA</a>
<ul>
<li data-num-products="3"><a href="...">BBB</a></li>
<li data-num-products="0"><a href="...">CCC</a></li>
</ul>
</li>
<li data-num-products="7"><a href="">DDD</a></li>
</ul>
<nav>
</nav>
Given 1 level of nesting ul‘s, I want to remove any li‘s that…
-
have no nested
ul‘s within them and -
have
data-num-products == 0.
So in the example above AAA is retained because it has ul children, but CCC is removed because it has no ul children and no products.
UPDATE:
It might require 2 passes of removal because if a li contains a ul whose li elements are all removed, then we’ll want to remove the ul too.
1 Answer