Removing Elements from the DOM

Hey ,

I'm thrilled to help you learn JavaScript. Unfortunately, you've landed on a page where you cannot access with your current purchase.

Please upgrade (use this link) access this content.

I'm super eager to help you learn more!

Removing Elements from the DOM

You can remove an element with parentNode.removeChild.

Let’s see it in action. Say you want to remove Jen Simmons from the list below.

<ol>
  <li>Rachel Andrew</li>
  <li>Jen Simmons</li>
  <li>Una Kravets</li>
</ol>

You’ll first get Jen with querySelector, then remove it with removeChild.

const jen = document.querySelectorAll('li')[1]
jen.parentNode.removeChild(jen)

The result is:

<ol>
  <li>Rachel Andrew</li>
  <li>Una Kravets</li>
</ol>

Moving the HTML element

removeChild returns the Element you removed. You then use appendChild or insertBefore to move the element.

Let’s say you want to move Jen from the second position to the first position in the following HTML.

<ol>
  <li>Rachel Andrew</li>
  <li>Jen Simmons</li>
  <li>Una Kravets</li>
</ol>

To do so, you need to get jen with removeChild, then add jen back into the list with insertBefore.

const list = document.querySelector('ol')
const rachel = list.children[0]

const jen = list.removeChild(list.children[1])
list.insertBefore(jen, rachel)

The result is:

<ol>
  <li>Jen Simmons</li>
  <li>Rachel Andrew</li>
  <li>Una Kravets</li>
</ol>

Exercise

  1. Remove Aragorn from the following HTML.
  2. Add it to the end of the list.
<ol class="humans">
  <li>Gandalf</li>
  <li>Saruman</li>
  <li>Aragorn</li>
  <li>Boromir</li>
  <li>Faramir</li>
</ol>

Answers

const humans = document.querySelector('.humans')
const aragorn = humans.children[2]
humans.removeChild(aragorn)
humans.appendChild(aragorn)