JavaScript Code

How to remove first child of div using JavaScript?

Tutorials using JS

Remove first child of div

given a div element in the document, remove the first child element of the given div element, using JavaScript


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


where myDiv is the div element from which we need to delete the first 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 first child from the div’s children

<!DOCTYPE html>
<h1>JavaScript Tutorial</h1>
<h2>Delete first 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 first child of div


Copyright @2022