Difference between :last and :last-child selector in jQuery / :last Vs :last-child selector in jQuery

 :last Selector – Meaning and Usage

:last selector fetches the last element from the collection of elements matched using a selector. Example, $("span") will select all span elements on the page. Adding the :last selector to the $("span") will return the last span out of those.
If :last selector is used with another selector then, first the elements matching that selector are retrieved and then out of selected elements, those elements which are last in this list is returned. Example, $("span.source:last") will first retrieve those span elements which have the class source and then out of this collection, the last span is returned.

:last-child selector – Meaning and Usage

:last-child matches all those elements which are last children of their parents. Example, $("span:last-child") will match all those span elements which are the last child of their parent.
When :last-child is used with another selector, then first the elements matching that selector are retrieved and then out of selected elements, those elements which are last child of their parent are returned. Example, $("input.source:last-child") will first match all input elements which have class source. Then, out of these input elements, those which are the last child of their parent are returned.

Difference between :last and :last-child Selectors

Based on the above discussion on :last and :last-child selectors, following are the differences between the two.

S. No. :last selector :last-child selector
1. Returns the element which is last from among the elements matched by a selector. Example, $("span.source:last") will return the last span from among those spans which have source class. Returns the element which is last child of its parent from among the elements matched by a selector. Example, $("span.source:last-child") will return those span elements which have class source and which are also the last child of their parents.
2.  :last selector will return only one element.  :last-child selector will return a collection of elements. Note that all elements in the collection will be the last child of their parents.

Examples of :last selector

Selector Returns
$(“div span:last”) Last span out of those which are inside a div
$(“table tr:last”) All tr elements which are last in their table
$(“input.check:last”) Last input from all input elements having class check
$(“p:last”) Last paragraph element on the page

Examples of :last-child selector

Selector Returns
$(“div span:last-child”) All span which are last child of a div
$(“table tr:last-child”) All tr elements which are last in their table
$(“input.check:last-child”) All input elements having class check and which are last child of their parents
$(“p:last-child”) All paragraph elements which are the last child of their parents

Leave a Reply