How to Select the Last Element Using jQuery last()
This article explains how to select and manipulate the final element
of a specific type in the DOM using jQuery's built-in
.last() method. You will learn the correct syntax, see
practical code examples demonstrating its application, understand the
performance benefits of using the .last() method over
alternative selectors, and discover how to handle common edge cases like
selecting the last item across multiple parent containers.
Understanding the
.last() Method
The jQuery .last() method reduces the set of matched
elements to the very last one in the collection. It operates on an
existing jQuery object and returns a new jQuery object containing only
the final element.
Basic Syntax
$('selector').last();Practical Example
Consider the following HTML markup:
<ul id="fruit-list">
<li class="fruit">Apple</li>
<li class="fruit">Banana</li>
<li class="fruit">Cherry</li>
<li class="fruit">Date</li>
</ul>To select the last <li> element with the class
fruit and change its text color, use:
$(document).ready(function() {
$('.fruit').last().css('color', 'red');
});In this example, jQuery first queries the DOM for all elements
matching .fruit. The .last() method then
isolates the final item ("Date") and applies the CSS change.
.last() Method vs.
:last Selector
jQuery offers two primary ways to target the last element: the
.last() traversal method and the :last
pseudo-selector.
- Traversal Method:
$('p').last() - Selector Extension:
$('p:last')
Using the .last() method is generally preferred for
performance. When you run $('p').last(), the browser uses
its fast, native querySelectorAll engine to grab all
<p> tags first, and jQuery simply extracts the final
index. The :last pseudo-selector is a non-standard jQuery
extension, meaning the query cannot be fully optimized by the browser's
native CSS engine.
Selecting the Last Element Across Multiple Containers
A common pitfall occurs when trying to select the last item in
each container on a page. The standard .last()
method returns only the single absolute last element of the entire
matched set.
For example, if you have two lists:
<ul class="list">
<li>Item 1A</li>
<li>Item 1B</li>
</ul>
<ul class="list">
<li>Item 2A</li>
<li>Item 2B</li>
</ul>Running $('.list li').last() will select only
Item 2B.
If your goal is to select the last element within each
distinct group, use the CSS :last-child pseudo-class
instead:
$('.list li:last-child').css('font-weight', 'bold');Alternatively, you can iterate over each container using
.each() and apply .last() inside the loop:
$('.list').each(function() {
$(this).find('li').last().css('font-weight', 'bold');
});