user1173169
user1173169

Reputation:

How can I access the second to last child?

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

Answers (5)

Mark Walters
Mark Walters

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

BenM
BenM

Reputation: 53198

Just using prev() should suffice:

$('ul#selectTheme li:last').prev('li').addClass('selected');

jsFiddle Demo

Upvotes: 1

joeytwiddle
joeytwiddle

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

Rich O'Kelly
Rich O'Kelly

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

user247702
user247702

Reputation: 24212

Try using the :nth-last-child() selector:

$('ul#selectTheme li:nth-last-child(2)').addClass('selected');

Upvotes: 4

Related Questions