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

Solution

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

myDiv.removeChild(myDiv.firstElementChild);

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

<!DOCTYPE html>
<html>
<body>
<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>
</div>
<pre id="output"></pre>

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

</body>
</html>

Copyright @2022