I would like to target the first and last ‘li’ of a ‘ul’ using jQuery and add a class of “first” and “last” to them accordingly.
I know that using jQuery this is easy if its just a simple ‘ul’ but I am struggling with the right syntax if the ‘ul’ has more than one ‘ul’ nested in the parent ‘ul’.
Here is an example of the html markup:
<ul>
<li><a href="#">Top Level Item</a>
<ul>
<li><a href="#">First Sub-Item</a></li>
<li><a href="#">Last Sub-Item</a>
<ul>
<li><a href="#">First Sub-Sub-Item</a>
<li><a href="#">Last Sub-Sub-Item</a></li>
</li>
</ul>
</li>
</ul>
</li>
</ul>
I need to target all of the first and last items of each sub-ul and apply a class to each of them.
Here is what I have been using but it is obviously not working as it is applying the class name to only the very first ‘li’ and the very last ‘li’.
jQuery('.topmenu ul li ul li').first().addClass('first');
jQuery('.topmenu ul li ul li').last().addClass('last');
Any suggestions?
I’ll assume that everything you have shown is inside something with the class “topmenu”. I would advise changing this to an ID if it’s unique, and applying a class to the “first ul” so it doesn’t have to be avoided algorithmically.
http://jsfiddle.net/aBksB/2/
EDIT: to reflect comment