JavaScript Code


How to remove last child of div using JavaScript?


Tutorials using JS

Remove last child of div

Given a div element in the document, remove the last child element of the given div element, using JavaScript.

Solution

To remove the last child element from the children of the given div element, use Element.removeChild() method. call removeChild() method on the div element, and pass the last child as argument to the method.

myDiv.removeChild(myDiv.lastElementChild);

where myDiv is the div element from which we need to delete the last child.

Program

In the following HTML code, we have a div element #myDiv with three children. when user clicks on the button Click Me, we will delete the last child from the div’s children.

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Tutorial</h1>
<h2>Delete last child of div</h2>
<button id="myBtn">Click me</button><br>
<div id="myDiv">
  <div>Child 1</div>
  <div>Child 2</div>
  <div>Child 3</div>
</div>
<pre id="output"></pre>

<script>
document.getElementById("myBtn").addEventListener("click", function() {
  //get div element
  const myDiv = document.getElementById("myDiv");
  //remove last child of div
  myDiv.removeChild(myDiv.lastElementChild);
});
</script>

</body>
</html>

Copyright @2022