views:

317

answers:

3

I want to apply a special class to the two last list items in an unordered list with jQuery. Like this:

<ul>
<li>Lorem</li>
<li>ipsum</li>
<li>dolor</li>
<li class="special">sit</li>
<li class="special">amet</li>
</ul>

How to? Should I use :eq somehow?

Thanks in advance

Pontus

+1  A: 
var items = $('ul li')
var last_two = items.filter('li:gt('+ items.length-3 +')')
last_two.addClass('special');
defrex
alternatively: items.slice(items.length - 2).addClass('special')
Marc
Add as an answer :P
jakemcgraw
Thanks a lot, but what do I then do with the variable "last_two"?
ponjoh
last_two.addClass("special");
Marc
+1  A: 
$(function(){

  $("li:gt("+($("li").length-3)+")").addClass("special");

});
jakemcgraw
+3  A: 

Another approach, using andSelf and prev:

$('ul li:last-child').prev('li').andSelf().addClass("special");
CMS
Thank you! That worked beautifully!
ponjoh
@ponjoh: You're welcome!
CMS