Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select penultimate (last but one) li element from the ul list in jQuery?

Tags:

jquery

If I have something like this:

<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>

and I need to addClass "extra" to the penultimate (e.g. if I have 5 li elements the extra class will be added to the 4th li element) from the ul list.

so the result in this case will be:

<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li class="extra">4</li>
<li>5</li>
</ul>

Thanks in advance

like image 441
killingon Avatar asked Aug 16 '11 18:08

killingon


2 Answers

$("li:last").prev("li").addClass("class-to-add")

http://api.jquery.com/prev/

http://api.jquery.com/last-selector/

like image 131
Dan Williams Avatar answered Sep 20 '22 15:09

Dan Williams


If there's only one list, just pass a negative index to the eq()[docs] method.

$("ul li").eq(-2).addClass("extra");

Sounds like you're using an older version of jQuery.

Here's an example that shows it working in jQuery 1.3.2.

like image 23
user113716 Avatar answered Sep 21 '22 15:09

user113716