user3384985 user3384985 - 6 months ago 22
Javascript Question

jQuery find a class and create callback for its last element

In 'jQuery' I can execute callback for all elements of a class like this way -

jQuery(form_id).find(".multiple_upldprev").each(function () {


But I want to execute only last element of the class. I tried this way -

jQuery(form_id).find(".multiple_upldprev").last(function () {


It doesn't work.

How can I do that?

Answer

last() will reduce the set of matched elements to the final one in the set. And it does not take a handler. You can use:

$(...).last().each(function() {

});

Which usually doesn't make sense since .last() just returns the element:

var $lastElement = $(...).last();
// Do something with $lastElement

In cases where you have a predefined handler each might make sense:

$(...).last().each(myHandler);
// The same can roughly be archived with:
myHandler.call($(...).get(-1));