30 Days Of JavaScript

Day 16: DOM Manipulation

Lesson 2: Deleting DOM Elements

.remove()

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];
3console.log(simon);
4simon.remove();

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.

.removeChild()

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>
6</ul>

and your JavaScript to this:

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

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);
3}

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.

Outline

Go Pro?

If you upgraded to pro, sign in here

  • About
  • Blog
  • Privacy
Looking to email me? You can get me on my first name at allthecode.co