The Web Developer Bootcamp 2024

Colt Steele

Back to DOM Index Page


Parent | Child | Sibling
removeChild

removeChild() works similar to appendChild() except that we are removing as opposed to adding a child element. When using appendChild, we are adding a new element to an existing parent element and removeChild works the same way. We are not just creating a NEW element on the webpage, we are removing a child element from an existing parent element.

Let's create an unordered list to demonstrate:

This is an unordered List [ul]

  • Item One
  • Item Two
  • Item Three
    • Sub-Item One
    • Sub-Item Two
  • Item Four
  • Item Five

and in an unordered List [ul], all of [li]'s are children of the parent [ul] element.

1. first off, we need to define the child element we want to remove, in this example we are going to remove Item Two from the list:
  1. const remItem = document.querySelectorAll('li')[1];
    1. selects the 2nd list item [Item Two]
2. next, we need to define the parent element that we are removing a child from:
  1. const unordList = remItem.parentElement;
    1. selects the parent element for remItem, which is the [ul] unordered list element
3. and now remove the child item from the parent:
  1. unordList.removeChild(remItem);
    1. removes the line item [li], remItem from the parent unordered list [ul] unordList

and we are left with:

  • Item One
  • Item Two
  • Item Three
    • Sub-Item One
    • Sub-Item Two
  • Item Four
  • Item Five
notice that the [li] Item Two has now been removed.

*note that you could also simplify the code by eliminating step 2, and changing step 3, like so:

  • remItem.parentElement.removeChild(remItem);




remove

remove is a newer method that allows us to remove an element. But what's nice with remove is that with this method, we no longer have to define the parent element.

The syntax is very simple:

  • element.remove()
You simply define the element you wish to remove (usually as a variable), and remove it. No parent involved. If we use this on our unordered List example from above, in which we selected the 2nd list item for removal, and assigned it to the variable remItem, the code would be:
  • remItem.remove();

Back to Top