Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: Getting the two last list items?

Tags:

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

like image 335
ponjoh Avatar asked Aug 10 '09 21:08

ponjoh


People also ask

How do I get the second last Li in jQuery?

You need to use "nth-last-child(2)" of jquery, this selects the second last element.

What is slice () method in jQuery?

jQuery slice() Method This method is used to limit the selection of elements in a group, by a start and end point: the start parameter is a starting index (starts at 0) from which to create the subset, and the stop parameter is an optional ending point.

What is EQ jQuery?

jQuery eq() Method The eq() method returns an element with a specific index number of the selected elements. The index numbers start at 0, so the first element will have the index number 0 (not 1).

How can I get second child in jQuery?

grab the second child: $(t). children(). eq(1);


1 Answers

You can use function slice. It is very flexible.

$('ul li').slice(-2).addClass("special"); 
like image 161
vkostromin Avatar answered Oct 23 '22 13:10

vkostromin