Remove Child Elements with JavaScript removeChild

Web Design & Web Development
Sponsored links

In this article, I will introduce how to remove child elements with JavaScript removeChild.

What is removeChild?

The removeChild() is a Node method that removes the specified child node.
You can delete the specified child node by writing as follows.

let parent = document.getElementById('parent');
parent.removeChild(child);

Remove by specifying the id of the child element

Get the parent element and child element by id and remove only the child element.

HTML

<div id="parent">
  <div id="child">Child element</div>
</div>

JavaScript

//Get parent element
let parent = document.getElementById('parent');
//Get child element
let child = document.getElementById('child');
//Remove child element in parent element
parent.removeChild(child);
Sponsored links

Remove by specifying the class of the child element

Remove the elements with a specific class.

HTML

<div id="parent">
  <div class="child">Child element</div>
  <div class="child">Child element</div>
  <div class="child">Child element</div>
</div>

JavaScript

//Get parent element
let parent = document.getElementById('parent');
//Get child elements
let children = document.getElementsByClassName('child');
//Get the number of child elements
let len = children.length;

for(let i = 0; i < len; i++){
    parent.removeChild(children[0]);
}
Sponsored links

Remove all child elements

Remove all child elements that exist within the parent element.

HTML

<div id="parent">
  <div class="child">Child element</div>
  <div class="child">Child element</div>
  <div class="child">Child element</div>
</div>

JavaScript

//Get parent element
let parent = document.getElementById('parent');

while(parent.lastChild){
  parent.removeChild(parent.lastChild);
}