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
$("li:last").prev("li").addClass("class-to-add")
http://api.jquery.com/prev/
http://api.jquery.com/last-selector/
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.
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