• jQuery Video Tutorials

jQuery :last Selector



The :last selector is a jQuery selector that selects the last element in a set of matched elements.

When we apply this method to a set of matched elements, It returns the last element found within that set. If no elements match the selector expression, an empty jQuery object is returned.

Note: If we want to select the first element in a set of matched elements, we need to use the :first selector.

Syntax

Following is the syntax of jQuery :last selector −

$("selector:last")

Parameters

Following is the explantion of above syntax −

  • selector: This is a placeholder for CSS selector. It specifies the criteria for selecting elements. For example:
  • "div" selects all <div> elements.

  • ".class" selects all elements with the class "class".

  • "#id" selects the element with the id "id".

  • last: Filters the selection to the last element of the matched set.

Example 1

In the following example, we are using the :last selector to select the last "paragraph" element −

<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $("p:last").css("background-color", "grey");
    })
});
</script>
</head>
<body>
   <p>This is the first paragraph.</p>
   <p>This is the second paragraph.</p>
   <p>This is the third paragraph.</p>
<button>Click</button>
</body>
</html>

After executing the above program and clicking the button, it highlights the last <p> element with grey background color.

Example 2

In this example, we are selecting the last <div> element using the :last selector −

<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $("div:last").css("background-color", "grey");
    })
});
</script>
</head>
<body>
   <div>This is the first div.</div>
   <div>This is the second div.</div>
   <div>This is the third div.</div>
<button>Click</button>
</body>
</html>

When we click the button after executing, it selects the last <div> element in the DOM.

Example 3

Here, we are selecting the last element with class "highlight" using the :last selector −

<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $(".highlight:last").css("background-color", "grey");
    })
});
</script>
</head>
<body>
<p class="highlight">This is the first paragraph.</p>
<p>This is a second paragraph.</p>
<p class="highlight">This is LAST paragraph.</p>
<button>Click</button>
</body>
</html>

After executing the above program, it selects the last element with class "highlight" and highlights with grey background color.

jquery_ref_selectors.htm
Advertisements