jQuery Selector for Last List Item in Unordered List

Selecting the last list item in an unordered list using jQuery can be achieved using the :last selector, the :last-child pseudo-class, or the .last() traversal method. This guide demonstrates how to write each selector, explains how they differ, and highlights the best choice depending on whether your page contains a single list or multiple lists.

The :last Selector

The most direct way to select the final item is using jQuery's custom :last selector:

$('ul li:last')

This selector queries all unordered lists on the page, finds all list items within them, and selects only the single absolute last <li> element found in the entire document.

The :last-child Selector

If your page has multiple unordered lists and you want to target the last item of each list, use the standard CSS :last-child selector:

$('ul li:last-child')

Because :last-child is a native CSS pseudo-class, it is natively supported by modern browsers' querySelectorAll engines, making it faster in execution than jQuery's custom :last selector.

The .last() Traversal Method

Alternatively, you can select all list items and filter down to the final one using jQuery's .last() method:

$('ul li').last();

This method is especially useful when chaining operations or when you already have a cached jQuery collection of list items.

Practical Example

Here is a practical demonstration showing how to apply a CSS style to the last item:

$(document).ready(function() {
    // Highlights the last item in every unordered list
    $('ul li:last-child').css('font-weight', 'bold');
});

For most use cases, $('ul li:last-child') is the recommended choice due to better performance and predictable behavior across multiple lists.