To get the last child of a HTML element using jQuery, the simplest way is with the jQuery :last-child selector.

$("#div p:last-child");

Let’s say I have the following HTML:

This is the first child of #div1

This is the second child of #div1

This is the third child of #div1

This is the fourth child of #div1

To get the last paragraph child of the div, we can use the jQuery :last-child selector:

$("#div1 p:last-child");

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

jQuery("#div1 p:last-child");

How to Get the Last Child on Click using jQuery

We can get the last child of an HTML element using jQuery very easily by combining the :last-child selector with a click event.

Let’s say we have the following HTML code and we want to change the background color of the last paragraph.

This is paragraph 1

This is paragraph 2

This is paragraph 3

Change background

We can utilize the jQuery :last-child selector, and the jQuery css() method to change the background of the last paragraph.

Below is the Javascript code which will allow the user to be able to select the last paragraph and set the new background color using jQuery.

$("#click-me").click(function(){
    $("#div1 p:last-child").css("background","#c1e9c1");
}); 

The final code and output for this example of how to change the background of the last child of a div using jQuery and Javascript is below:

Code Output:

This is paragraph 1

This is paragraph 2

This is paragraph 3

Change background

Full Code:

This is paragraph 1

This is paragraph 2

This is paragraph 3

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

Hopefully this article has been useful to help you understand how to use jQuery to get the last child from a parent HTML element.

Categorized in:

jQuery,

Last Update: March 20, 2024