Rawi Rai Rawi Rai - 3 months ago 28
jQuery Question

how to use jquery addclass on parent ul by counting li?

i need to addclass on my parent ul by count li onload. here is example of my ul li.

for example count li inside submenu and add class there.





or something else class name that define li count.



<ul>
<li><a href="#">top 1st menu</a>
<ul>
<li><a href="#">sub menu</a></li>
<li><a href="#">sub menu</a></li>
</ul>
</li>
<li><a href="#">top 2nd menu</a>
<ul>
<li><a href="#">sub menu</a></li>
<li><a href="#">sub menu</a></li>
<li><a href="#">sub menu</a></li>
<li><a href="#">sub menu</a></li>
</ul>
</li>
</ul>





hope its clean. if not please let me know i will provide screenshot to clear more.

thank you

K K K K
Answer

Try this:

$("ul").addClass(function() {
    return ' ' + $(this).find(">li").length; //Change the class accordingly.
  });

Demo: http://jsfiddle.net/GCu2D/1467/

With a prefix:

 $("ul").addClass(function() {
    return 'sub' + $(this).find(">li").length; //Change the class accordingly.
  });

Demo: http://jsfiddle.net/GCu2D/1466/