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.


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.


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


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>
<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>
<pre id="output"></pre>

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


Copyright @2022