How to easily remove a DOM element with JavaScript

JavaScript offers two simple methods for DOM element removal.

Below are these methods with examples.

The remove() method

Using the remove() method, we can remove the element from the DOM.

Let’s say we have an unordered list with three items.

We want to remove this unordered list.

We can remove it with the use of the remove() method.

To do so we can use the remove() method
(click on the image to open in a new tab)

And the unordered list has now been removed.

The unordered list has successfully been removed from the DOM

The removeChild() method

The DOM’s removeChild() method, deletes a child node, returning the deleted node.

We can achieve the same thing with the use of the removeChild() method.
(click on the image to open in a new tab)

In the previous example, we removed the DOM element (ul) without specifying its parent node.

This is handy when we don’t know the parent node.

In our case, we know it, thus we have the option to use this method by specifying the parent node.

Knowing the parent node makes the code simpler to implement.
(click on the image to open in a new tab)

Suppose we want to use more than one children from an element.

In our case we want to remove all the li items from the unordered list.

We utilize a while loop to remove the children of the unorder list.
(click on the image to open in a new tab)

By using a while loop we are able to remove more than one child nodes from a parent node.

The parent node stays intact.

In our example we used the ul as the parent node, removing the li items.

The removeChild() method leaves the parent element intact.
(click on the image to open in a new tab)

Although my blog doesn’t support comments, feel free to reply via email or X.