jQuery Traversal - last() Method

Example

Highlight the last span in the paragraph:

$("p span").last().addClass('highlight');

Try it yourself

Definition and Usage

last() reduces the matched element collection to the last element in the collection.

Syntax

.last()

Detailed Description

If a jQuery object representing a collection of DOM elements is given, the .last() method will construct a new jQuery object using the last matching element.

Please think about the following page with a simple list:

<ul>
  <li>list item 1</li>
  <li>list item 2</li>
  <li>list item 3</li>
  <li>list item 4</li>
  <li>list item 5</li>
</ul>

We can apply this method to the collection of list items:

$('li').last().css('background-color', 'red');

Try it yourself

The result of this call is that the last item is set to a red background.