Reputation:
I'm trying to access the second to last li
. I tried following code, but it isn't working:
$('ul#selectTheme li:last').eq(-1).addClass('selected');
How can I do this?
Upvotes: 1
Views: 108
Reputation: 12390
I believe you can simply pass a minus number to .eq()
to get the nth element from the end. -1 being the last element and so forth.
$('ul#selectTheme li').eq(-2).addClass('selected');
Take a look here for more details - .eq()
Upvotes: 2
Reputation: 53198
Just using prev()
should suffice:
$('ul#selectTheme li:last').prev('li').addClass('selected');
Upvotes: 1
Reputation: 31285
Try this:
$('ul#selectTheme li').eq(-2).addClass('selected');
Your case seems much like one of the examples given in the documentation: http://api.jquery.com/eq/
Upvotes: 0
Reputation: 41757
You can just use the length property to get this:
var themes = $('#selectTheme li');
$(themes[themes.length - 2]).addClass('selected');
This has the added benefit of not using any of the slower jQuery pseudoselectors.
I have also omitted the ul
part of the selector, since this unnecessary - the id selector is specific enough.
Upvotes: 0
Reputation: 24212
Try using the :nth-last-child()
selector:
$('ul#selectTheme li:nth-last-child(2)').addClass('selected');
Upvotes: 4