views:

48

answers:

2

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>
</ul>

var lastLiId = $(".album li:last").attr("id"); // minus one?
+3  A: 

Probably a neater way but how about:

var lastLiId = $(".album li:last").prev("li").attr("id");
richsage
+7  A: 

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.

Nick Craver
Negative index is supported since 1.4.
KennyTM
aha, eq goes negative!
FFish
@KennyTM - It works in 1.3.2 as well: http://jsfiddle.net/nick_craver/nQeC8/1/ It's just a `.slice()` call underneath.
Nick Craver
@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
Nice. That's neat! Shame the eq docs don't mention it, that's a handy one to know :-)
richsage
@richsage - They do :) "Providing a negative number indicates a position starting from the end of the set, rather than the beginning", make sure you're looking at the `.eq()` docs and not the `:eq()` docs: http://api.jquery.com/eq/
Nick Craver
@Nick ... that would be the page I wasn't looking at :-) Cheers!
richsage