views:

98

answers:

2

Can someone explain the difference between .last() and :last ? I can't seem to find a definitive explanation.

Why Exactly does this $('td.cellsOfSpecificClass:last', '.table tr') return the last td in each tr instead of the last td in the whole table?

+5  A: 

The .last() is a function which returns the last element of the given (existing) collection of elements. The :last is a selector which is to be used in $('...') which immediately returns the last element instead of a whole collection. Which one to use depends on what you've as far and what you need.


Update: to clarify the last phrase a bit more:

If you already have a collection of elements in a variable at the moment you need the last element, then use .last(). If you don't already have it and you just need only the last element, then use :last. If you actually need both in the remnant of the code, then grab all elements and use .last().

BalusC
What did you mean to say in your last sentence?
CIDIC
+2  A: 

This is more to elaborate on BalusC answer in case of mis-understanding, so please up-vote his, ya?

the 'given array' is an array of jQuery elements.

$('.willReturnManyObjects').last()

will give you a jQuery object that's the last element found with that class name / selector.

This is the same as calling .eq(-1);

:last is to get the last item in the selector, but could be used to get many elements:

$('input:last, .extraDiv'); 

this would give you the LAST input and any .extraDiv elements.

Cool, eh?

edit: looks like BalusC edited his answer to be a bit more understandable while i was typing this :p

Dan Heberden
+1 for honesty and being honorable with regard to whose answer was first and/or more succinct. (Don't worry, I gave +1 to the other one too!) :-)
Platinum Azure
why would $('input:last, .extraDiv'); select the last input AND .extraDiv? isn't .extraDiv the context of the query for input?
CIDIC
no, because the comma is _inside_ the apostrophes - jquery is getting only one argument, the string literal with the selectors. Had the comma been outside, such as `$('input:last, .extraDiv', $contextElement);` then it would search by context..
Dan Heberden
Duh, I don't know why I read that wrong.
CIDIC