views:

7772

answers:

4

Howdy Guys,

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!

A: 

you can try

$('#sidebar ul li:last').addClass('last');
smoothdeveloper
+14  A: 

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.

cletus
thanks for the tip, never tripped on that now
smoothdeveloper
Perfect! - Thanks for taking the time to help me out mate, appreciate it
Keith Donegan
+3  A: 

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.

cdmckay
A: 

Or you could give your list an id and use that as an context to jquery-call.

<ul id="myList">
  <li>Item</li>
  <li>Item</li>
  <li>Item</li>
  <li>Item</li>
</ul>

<ul id="anotherList">
  <li>Item</li>
  <li>Item</li>
  <li>Item</li>
  <li>Item</li>
</ul>

And then you can do:

jQuery("li:last", "ul#myList").addClass("lastItem");

Now the last li in the first list would have class "lastItem".

Edit: Sorry, misread the question. Ignore this please.