30 Days Of JavaScript

Day 16: DOM Manipulation

Lesson 2: Deleting DOM Elements


Once you have an element from the DOM in JavaScript, you can tell it to remove it's self from the DOM with the .remove() method. Let's take a look, change your JavaScript code to look like this.

1const titles = document.getElementsByClassName("title-small");
2const simon = titles[0];

When you hit save you will see that "Hello Simon" is removed from the DOM!

However, like I said earlier your index.html page doesn't change, that paragraph is still there, it's the version that is displayed in the browser that has changed.


What about if we want to remove all the child elements from a specific HTML element? Well we can do that with .removeChild().

Replace your HTML with this.

1<ul id="todos">
2  <li>Clean kitchen</li>
3  <li>Go for a run</li>
4  <li>Cook lunch</li>
5  <li>Walk dog</li>

and your JavaScript to this:

1const todos = document.getElementById("todos");
3while (todos.hasChildNodes()) {
4  todos.removeChild(todos.children[0]);

You'll know this worked because your screen will be blank. Let's take a look at the code.

We get the parent unordered list tag <ul> and store it in todos.

Then we set up a while loop that will run until todos.hasChildNodes() returns false (which it will once we delete them all).

And then in the while loop each iteration we delete the first element in the children. Each time we delete one the loop rechecks hasChildNodes() and runs again until it's empty, each time we delete the first child all the others move down one so eventually they will all be in the first position and so will all get deleted.

The reason we can't do something like this

1todos.children.forEach((child) => child.remove());

Is because forEach is a method only available on arrays and todos.children isn't an array, it's an object and so we can't iterate over it.

Now we know how to delete elements let's look at creating them.

A safer (as in, less likely to cause a problem in your code) approach to deleting all children is this function variation of the above

1while (todos.firstChild) {
2  todos.removeChild(todos.lastChild);

It removes the last child of the list until there isn't a first child any more. In my experience this is more resilient to errors and weird bugs.


Go Pro?

Upgrade to Pro for quizzes, tracked progress and a completion certificate for just $25 🚀

Want more developer tips, tricks and tools?
Then follow me:
FREE Coding Career Quick Start Guide 🚀
Discover the best way to learn to code, how to land a job and valuable resources to help your journey in this free 15 page value packed guide.
Looking to email me? You can get me on my first name at allthecode.co