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");
});
Author by
ponjoh
Updated on June 08, 2022Comments
-
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 over 14 yearsalternatively: items.slice(items.length - 2).addClass('special')
-
ponjoh over 14 yearsThanks a lot, but what do I then do with the variable "last_two"?
-
Marc over 14 yearslast_two.addClass("special");
-
ricka over 10 yearsI wouldn't consider this "native".
-
ZalemCitizen over 3 yearsandSelf() was deprecated since jQuery 1.8 and removed in 3.0