15

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!

Keith Donegan
  • 26,213
  • 34
  • 94
  • 129
  • Is this added class used to add a margin at the bottom of the list? If so, you could just use the ul's margin-bottom property instead. If not, carry on. =P – EndangeredMassa Feb 19 '09 at 02:54
  • Also, you don't need to do `.each` in this case, you can just do `.addClass` directly. jQuery will apply all commands to the entire set of matched elements. – cdmckay Feb 19 '09 at 02:58
  • Also, a good site to test out different selectors and see how they work can be found here: http://www.woods.iki.fi/interactive-jquery-tester.html – cdmckay Feb 19 '09 at 03:05

6 Answers6

36

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
  • 616,129
  • 168
  • 910
  • 942
4

with jquery add this

$("ul li").last().addClass('last');
Ayham
  • 131
  • 1
  • 4
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.

cdmckay
  • 31,832
  • 25
  • 83
  • 114
0

If you need to add class to 3 separate lists you can assign a class for them and use 'each':

$('#sidebar ul.class li:last-child').each(function(e){
    $(this).addClass("last");
});

This should work exactly as you expected.

Burning
  • 11
  • 3
0

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.

-1

you can try

$('#sidebar ul li:last').addClass('last');
smoothdeveloper
  • 1,972
  • 18
  • 19