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

42,768

Solution 1

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.

Solution 2

with jquery add this

$("ul li").last().addClass('last');

Solution 3

The reason that won't work is due to the fact that :last only matches one element. From the jQuery documentation:

Matches the last selected element.

So what your code is doing is getting a set of all the <li> elements in a <ul> and then from that set taking the last value. Example:

 <ul>
   <li>1</li>
   <li>2</li>
 </ul>
 <ul>
   <li>3</li>
   <li>4</li>
 </ul>
 <ul>
   <li>5</li>
   <li>6</li>
 </ul>

Your code would return the element <li>6</li>. (Internally, it'd collect <li>1</li> to <li>6</li> and then lop off the last one and return it).

What you're looking for is what the other answers here have said: :last-child.

Share:
42,768
Keith Donegan
Author by

Keith Donegan

Just another Developer...

Updated on December 06, 2020

Comments

  • Keith Donegan
    Keith Donegan over 3 years

    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!