Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 318
Keith Donegan Avatar asked Feb 19 '09 02:02

Keith Donegan


3 Answers

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.

like image 59
cletus Avatar answered Oct 01 '22 04:10

cletus


with jquery add this

$("ul li").last().addClass('last');
like image 21
Ayham Avatar answered Oct 01 '22 05:10

Ayham


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.

like image 28
cdmckay Avatar answered Oct 01 '22 05:10

cdmckay