Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery selector before-last

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? 
like image 644
FFish Avatar asked Oct 11 '10 10:10

FFish


People also ask

How to get prev element in jQuery?

jQuery prev() MethodThe prev() method returns the previous sibling element of the selected element. Sibling elements are elements that share the same parent. The DOM tree: This method traverse backwards along the previous sibling of DOM elements.

How do I get the second last Li in jQuery?

You need to use "nth-last-child(2)" of jquery, this selects the second last element.

What is prevObject in jQuery?

jQuery returns prevObject if the DOM does not have the element for which jQuery is being run. You might see the element in your source at the run-time however, it is not not bound to the DOM and therefore, it shows prevObject.

Is last child jQuery?

It is a jQuery Selector used to select every element that is the last child of its parent. Return Value: It selects and returns the last child element of its parent.


2 Answers

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.

like image 81
Nick Craver Avatar answered Sep 29 '22 01:09

Nick Craver


Probably a neater way but how about:

var lastLiId = $(".album li:last").prev("li").attr("id"); 
like image 29
richsage Avatar answered Sep 29 '22 02:09

richsage