I was wondering if there is any difference between .filter(':last')
and .last()
?
For me it looks like they're doing the same, but I'm new to jQuery. If there is no difference in the result, which one is remended or is it just a matter of personal preference?
I was wondering if there is any difference between .filter(':last')
and .last()
?
For me it looks like they're doing the same, but I'm new to jQuery. If there is no difference in the result, which one is remended or is it just a matter of personal preference?
Share Improve this question edited Sep 4, 2013 at 20:59 user1228 asked Jun 12, 2013 at 22:05 eLwoodianereLwoodianer 6746 silver badges12 bronze badges 2- 1 They do the same thing, and for most cases you''ll never notice the difference. – adeneo Commented Jun 12, 2013 at 22:07
- 2 The first one operates on all elements, running a non-standard selector against each one. The second one just grabs the last element from the jQuery object, and returns it in a new object. – user2437417 Commented Jun 12, 2013 at 22:14
2 Answers
Reset to default 6last
works by saying "give me the last element from the selection". It takes just two function calls and four lines of code to do so. It can't be done in a quicker way.
filter(':last')
, however, is much more plex. It is a much more flexible system, allowing multiple elements to be returned if that's what you want, or multiple conditions, or a mixture of both. It is much less efficient, because it has to work out what you want. For instance, parsing ':last'
takes a little time, whereas with the last
function it's a simple property lookup.
last
is by far the more efficient.
:last
- Selects the last matched element.
last()
- Reduce the set of matched elements to the final one in the set.
As you can see, they do the same thing (in terms of the end result, anyway).
last()
is slightly faster than :last (although you may not notice it, it's always good to know).
.filter(":last")
, although making the best (performance-wise) out of :last
, still involves more function calls and is still slower than last()
- although it does have its advantages (see @lonesomeday's answer for those).
My remendation however would be to generally use last()
as opposed to the former.