.last()


.last()Returns: jQuery

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

  • version added: 1.4.last()

    • This method does not accept any arguments.

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

Consider a page with a simple list on it:

1
2
3
4
5
6
7
<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 set of list items:

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

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

Example:

Highlight the last item in a list.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>last demo</title>
<style>
.highlight {
background-color: yellow;
}
</style>
<script src="https://code.jquery.com/jquery-3.7.1.js"></script>
</head>
<body>
<ul>
<li>Look:</li>
<li>This is some text in a list.</li>
<li>This is a note about it.</li>
<li>This is another note about it.</li>
</ul>
<script>
$( "ul li" ).last().addClass( "highlight" );
</script>
</body>
</html>

Demo: