jQuery: Getting the two last list items?

18,836

Solution 1

Another approach, using andSelf and prev:

$('ul li:last-child').prev('li').andSelf().addClass("special");

Solution 2

You can use function slice. It is very flexible.

$('ul li').slice(-2).addClass("special");

Solution 3

var items = $('ul li')
var last_two = items.filter('li:gt('+ items.length-3 +')')
last_two.addClass('special');

Solution 4

$(function(){

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

});
Share:
18,836
ponjoh
Author by

ponjoh

Updated on June 08, 2022

Comments

  • ponjoh
    ponjoh almost 2 years

    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

  • Marc
    Marc over 14 years
    alternatively: items.slice(items.length - 2).addClass('special')
  • ponjoh
    ponjoh over 14 years
    Thanks a lot, but what do I then do with the variable "last_two"?
  • Marc
    Marc over 14 years
    last_two.addClass("special");
  • ricka
    ricka over 10 years
    I wouldn't consider this "native".
  • ZalemCitizen
    ZalemCitizen over 3 years
    andSelf() was deprecated since jQuery 1.8 and removed in 3.0