Take the 2-minute tour ×

I have a dynamic list and need to select the before last item.

<ul class="album">
    <li id='li-1'></li>
    <!-- ... -->
    <li id='li-8'></li>
    <li id='li-9'></li>
    <li class='drop-placeholder'>drag your favorites here</li>

var lastLiId = $(".album li:last").attr("id"); // minus one?
share|improve this question
add comment

2 Answers

up vote 25 down vote accepted

You can use .eq() with a negative value (-1 is last) to get n from the end, like this:

$(".album li").eq(-2).attr("id"); // gets "li-9"

You can test it here.

Given the comments below, I want to be clear that this works in jQuery 1.3 as well (test it here), it's not 1.4+ specific, .eq() has always accepted negative numbers (though the docs say 1.4)...it just didn't accept -1 specifically. -2 or any other value works prior to 1.4, only .eq(-1) requires jQuery 1.4+, and we're not using that here.

share|improve this answer
Negative index is supported since 1.4. –  KennyTM Oct 11 '10 at 10:37
aha, eq goes negative! –  FFish Oct 11 '10 at 10:37
@KennyTM - It works in 1.3.2 as well: jsfiddle.net/nick_craver/nQeC8/1 It's just a .slice() call underneath. –  Nick Craver Oct 11 '10 at 10:38
@KennyTM, @FFish - To be clear, support for -1 specifically was added in 1.4, other negative indexes worked preior. Old version: eq: function( i ) { return this.slice( i, +i + 1 ); }, New version: eq: function( i ) { return i === -1 ? this.slice( i ) : this.slice( i, +i + 1 ); } –  Nick Craver Oct 11 '10 at 10:44
Nice. That's neat! Shame the eq docs don't mention it, that's a handy one to know :-) –  richsage Oct 11 '10 at 10:45
show 2 more comments

Probably a neater way but how about:

var lastLiId = $(".album li:last").prev("li").attr("id");
share|improve this answer
add comment

Your Answer


