.last() in JQuery


Description: Reduce the set of matched elements to the final one in the set.

  • version added: 1.2.last()

Given a jQuery object that represents a set of DOM elements, the .last() method constructs a new jQuery object from the first matching element.

Consider a page with a simple list on it:

  <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>

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

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

The result of this call is a red background for the final item.


Highlight the last span in a paragraph.

<!DOCTYPE html>
  <style>.highlight{background-color: yellow}</style>
  <script src="/scripts/jquery-1.4.js"></script>
	<p><span>Look:</span> <span>This is some text in a paragraph.</span> <span>This is a note about it.</span></p>
<script>$("p span").last().addClass('highlight');</script>



Leave a Reply

Your email address will not be published. Required fields are marked *