Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add class to the last <li> in a group of <ul>

I have a group of <ul>'s created dynamically and i need a class added to the last <li> of each one.

I have:

$('ul li:last').each(function(){
    $(this).addClass("last");
});

But this only adds a class="last" to the last <ul> not in all of the <ul>'s.

I want the last <li> of each <ul> to get added the class, not just the last <ul>.

like image 662
Xtian Avatar asked Dec 21 '22 02:12

Xtian


1 Answers

:last, a propriety jQuery selector, pops off the last element from the set and returns it.

:last-child, the CSS selector, selects the last child of each ancestor element.

$('ul li:last-child').addClass('last');

jsFiddle.

As a side note, you don't need to use each() there. The addClass() will be ran over each item in the jQuery set.

like image 149
alex Avatar answered Dec 31 '22 04:12

alex