removeChild method

The removeChild method allows you to remove an element. It applies to the parent element specifying the element to be removed.

Syntax

javascriptparent.removeChild(element);

Example

Let's remove the #elem paragraph. To do this, we get its parent #parent and the removeChild method is applied to the received parent, and the element we want to remove is passed as the method parameter:

html<div id="parent">
  <p id="elem">elem 1</p>
  <p>elem 2</p>
</div>
javascriptlet parent = document.querySelector('#parent');
let elem = document.querySelector('#elem');

parent.removeChild(elem);

The code execution result:

html<div id="parent">
  <p>elem 2</p>
</div>

Example

If you need to delete an element, but there is no reference to its parent, you can get the parent via parentElement:

html<div>
  <p id="elem">elem 1</p>
  <p>elem 2</p>
</div>
javascriptlet elem = document.querySelector('#elem');
elem.parentElement.removeChild(elem);

The code execution result:

html<div id="parent">
  <p>elem 2</p>
</div>

See also

  • the remove method
    that can be used to remove an element