How to empty the parent element in JavaScript

We can remove the children of the DOM element in 4 ways:

  • Removing all childrens
  • Setting innerHTML to empty string
  • Setting textContent to empty string
  • Using replaceChildren method

1. Removing all childrens

The remove method of the Element can be used to remove an element from the DOM. Using this, we can loop through all the child elements of the parent.

Console
Removing all childrens using "firstElementChild.remove()" method

The element.firstElementChild will return the first child of the parent. We will remove the firstElementChild of the parent as long as the parent has a child.

2. Setting innerHTML to empty String

By setting an empty string as innerHTML, we can remove all the children of an Element. When we set a value to innerHTML, JavaScript will parse the value using HTMLParser and replace the HTML content as parsed values – this may cause performance issues.

Console
Make the parent element empty using "innerHTML" property

3. Setting textContent to empty String

By setting an empty string as textContent, we can remove all the children of an Element. When we set a value to textContent, JavaScript will replace all children of the element with a #text node. This method is considered faster than innerHTML.

Console
Make the parent element empty using "textContent" property

4. Using replaceChildren method

The replaceChildren method replaces the children of a node with a specified new set of children. If we don’t send an argument, this method will remove all the children of the node in which it was called.

Console
Make the parent element empty using "replaceChildren()" method

Free Resources