In this tutorial we will learn how to Remove last child from parent element with jQuery. We can use jQuery remove() method with :last-child selector or children() method and last() method.
Table of Contents
jQuery remove() method
jQuery remove() method removes the selected HTML element and it's child elements.
In this example remove() method is used to remove the last child from parent element.
This code can be used to remove any last child of any parent tag.
:last-child Selector
:last-child Selector selects only last child of a parent tag.
jQuery children() method
jQuery children() method selects all children elements of the parent element.
jQuery last() method
jQuery last() method returns the last element from the list of HTML elements.
HTML Code
HTML Code is given below, in this code we have a parent div with five different child elements.
HTML button tag is used to execute a function.
<!DOCTYPE html>
<html>
<head>
<title>jQuery Remove last child from parent</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
</head>
<body>
<div id="parent">
<p>Text</p>
<a href="#">Link</a>
<div>Div</div>
<span>Span</span>
<h2>Heading</h2>
</div>
<button id="btn">Remove Last Child</button>
<script src="script.js"></script>
</body>
</html>
JQuery Code
JQuery Code is given below, jQuery click() method is used to trigger a function on click of a button.
Inside this function remove() method is used to delete last child tag.
$('#btn') is an id selector used to select the button tag.
$('#parent :last-child') is used to target or select the last child in the parent tag.
<script>
$(document).ready(function() {
$('#btn').click(function(){
$('#parent :last-child').remove();
});
});
</script>
We can also use children().last() to get the last child, in place of :last-child selector.
<script>
$(document).ready(function() {
$('#btn').click(function(){
$('#parent').children().last().remove();
});
});
</script>
Demo
Video Tutorial
Watch video tutorial on How To delete last child tag from parent tag using jQuery.