With the jQuery last() method, we can get the last element or div in a series of elements or divs.

$("div").last();

Let’s say we have the following HTML:

This is some text

This is some text

This is some text

This is some text

This is some text

This is some text

As we can see, we have three divs with class “divs”, each of which has two paragraphs. If we want to get the last div with class “divs” and change only its background color, we can do this using the jQuery last() method.

Here is the JavaScript code that would accomplish this:

$(".divs").last().css("background","green");

If you are using WordPress, don’t forget to change the $ to jQuery as below:

jQuery(".divs").last().css("background","green");

Using jQuery to Get the Last Div and Change its Background

In this example, we will get the last div of a series of divs with the same class using the jQuery last() method, and change its background color.

Here is our HTML setup with some styles added to the divs:


This is some text

This is some text

This is some text

This is some text

This is some text

This is some text

Change background

We can utilize the jQuery last() method, and the jQuery css() method to change the background of the last div.

Below is the Javascript code which will allow the user to be able to change the last div’s background color using jQuery.

$("#click-me").click(function(){
  $(".divs").last().css("background","#c1e9c1");
});

The final code and output for this example is below:

Code Output:

This is some text

This is some text

This is some text

This is some text

This is some text

This is some text

Change background

Full Code:


This is some text

This is some text

This is some text

This is some text

This is some text

This is some text

Change background
<script> $("#click-me").click(function(){ $(".divs").last().css("background","#c1e9c1"); }); </script>

Hopefully this article has been useful to help you understand the jQuery last() method.

Categorized in:

jQuery,

Last Update: February 26, 2024