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
You need to use "nth-last-child(2)" of jquery, this selects the second last element.
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.
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).
grab the second child: $(t). children(). eq(1);
You can use function slice. It is very flexible.
$('ul li').slice(-2).addClass("special");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With