LegendDemonSlayer
LegendDemonSlayer

Reputation: 1927

Find "ul" elements that does not have "li" elements using jquery

So lets say i have this html code

<ul id="mainUL">
<li>
   <ul></ul>
</li>
<li>
   <ul>
    <li>One</li>
    <li>Two</li>
   </ul>
</li>
<li>
   <ul>
   </ul>
</li>
</ul>

Is there a way to find those ul that does not contain any li elements? My code is quite dynamic so it is hard for me to insert a class or id to append those ul. Do i use jquery .find() or jquery .children()? And how do I apply these $('ul')?

Upvotes: 2

Views: 1569

Answers (1)

Mohammad
Mohammad

Reputation: 21489

You can use combine of :not() and :has() to do this work.

$("ul:not(:has(li))")

$("ul:not(:has(li))").css("border", "1px solid red");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="mainUL">
<li>
   <ul></ul>
</li>
<li>
   <ul>
    <li>One</li>
    <li>Two</li>
   </ul>
</li>
</ul>

Upvotes: 3

Related Questions