HTML DOM Element removeChild() Method

Definition and Usage

removeChild() This method removes the child nodes of an element.

This method returns the removed node as a Node object; if the node does not exist, it returns null.

Tip:

Child nodes are removed from the Document Object Model (DOM).

However, the returned node can be modified and inserted back into the DOM (see the example below).

See also:

remove() method

appendChild() method

insertBefore() method

replaceChild() method

childNodes attribute

firstChild attribute

lastChild attribute

firstElementChild attribute

lastElementChild attribute

Instance

Example 1

Remove the first element from the list:

const list = document.getElementById("myList");
list.removeChild(list.firstElementChild);

Before deletion:

  • Coffee
  • Tea
  • Milk

After deletion:

  • Tea
  • Milk

Try It Yourself

Example 2

If the list has child nodes, delete the first one (index 0):

const list = document.getElementById("myList");
if (list.hasChildNodes()) {
  list.removeChild(list.children[0]);
}

Try It Yourself

Example 3

Remove all child nodes from the list:

const list = document.getElementById("myList");
while (list.hasChildNodes()) {
  list.removeChild(list.firstChild);
}

Try It Yourself

Example 4

Remove an element from its parent node:

element.parentNode.removeChild(element);

Try It Yourself

Example 5

Remove an element from its parent element and then insert it again:

const element = document.getElementById("myLI");
function removeLi() {
  element.parentNode.removeChild(element);
}
function appendLi() {
  const list = document.getElementById("myList");
  list.appendChild(element);
}

Try It Yourself

Example 6: Prompt

Please use appendChild() or insertBefore() to insert the deleted node into the same document.

You can use document.adoptNode() or document.importNode() to insert it into another document.

The following example deletes an element from its parent element and inserts it into another document:

const child = document.getElementById("mySpan");
function remove() {
  child.parentNode.removeChild(child);
}
function insert() {
  const frame = document.getElementsByTagName("IFRAME")[0]
  const h = frame.contentWindow.document.getElementsByTagName("H1")[0];
  const x = document.adoptNode(child);
  h.appendChild(x);
}

Try It Yourself

Syntax

element.removeChild(node)

or

node.removeChild(node)

Parameter

Parameter Description
node Required. The node (element) to be deleted.

Return Value

Type Description
Node

The deleted node (element).

If the child node does not exist, it will be null.

Browser Support

element.removeChild() It is a DOM Level 1 (1998) feature.

All browsers fully support it:

Chrome IE Edge Firefox Safari Opera
Chrome IE Edge Firefox Safari Opera
Support 9-11 Support Support Support Support