JQuery - How to add a class to every last list item?

Keith Donegan picture Keith Donegan · Feb 19, 2009 · Viewed 41.9k times · Source

Got some code here that isn't working:

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

Basically I have 3 lists and want to add a class (last) to each item appearing last in each unordered list.

<ul>
      <li>Item 1</li>
      <li>Item 2</li>
      <li class="last">Item 3</li>
</ul>

Hope that makes sense, Cheers!

Answer

cletus picture cletus · Feb 19, 2009

Easy mistake to make. Try this:

$("#sidebar ul li:last-child").addClass("last");

Basically :last doesn't quite do what you think it does. It only matches the very last in the document, not the last in each list. That's what :last-child is for.