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?
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.
You need to use "nth-last-child(2)" of jquery, this selects the second last element.
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.
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.
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.
Probably a neater way but how about:
var lastLiId = $(".album li:last").prev("li").attr("id");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With