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:
<div id="div1">
<p>This is the first child of #div1</p>
<p>This is the second child of #div1</p>
<p>This is the third child of #div1</p>
<p>This is the fourth child of #div1</p>
</div>
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.
<div id="div1">
<p>This is paragraph 1</p>
<p>This is paragraph 2</p>
<p>This is paragraph 3</p>
</div>
<div id="click-me">Change background</div>
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
Full Code:
<div id="div1">
<p>This is paragraph 1</p>
<p>This is paragraph 2</p>
<p>This is paragraph 3</p>
</div>
<div id="click-me">Change background</div>
<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.
Leave a Reply