dom / latest / node / removechild.html /

Node.removeChild()

The removeChild() method of the Node interface removes a child node from the DOM and returns the removed node.

Note: As long as a reference is kept on the removed child, it still exists in memory, but is no longer part of the DOM. It can still be reused later in the code.

If the return value of removeChild() is not stored, and no other reference is kept, it will be automatically deleted from memory after a short time.

Unlike Node.cloneNode() the return value preserves the EventListener objects associated with it.

Syntax

removeChild(child);

Parameters

child

A Node that is the child node to be removed from the DOM.

Exception

NotFoundError DOMException

Thrown if the child is not a child of the node.

TypeError

Thrown if the child is null.

Examples

Simple examples

Given this HTML:

<div id="top">
  <div id="nested"></div>
</div>

To remove a specified element when knowing its parent node:

let d = document.getElementById("top");
let d_nested = document.getElementById("nested");
let throwawayNode = d.removeChild(d_nested);

To remove a specified element without having to specify its parent node:

let node = document.getElementById("nested");
if (node.parentNode) {
  node.parentNode.removeChild(node);
}

To remove all children from an element:

let element = document.getElementById("top");
while (element.firstChild) {
  element.removeChild(element.firstChild);
}

Causing a TypeError

<!--Sample HTML code-->
<div id="top"> </div>
let top = document.getElementById("top");
let nested = document.getElementById("nested");

// Throws Uncaught TypeError
let garbage = top.removeChild(nested);

Causing a NotFoundError

<!--Sample HTML code-->
<div id="top">
  <div id="nested"></div>
</div>
let top = document.getElementById("top");
let nested = document.getElementById("nested");

// This first call correctly removes the node
let garbage = top.removeChild(nested);

// Throws NotFoundError
garbage = top.removeChild(nested);

Specifications

Browser compatibility

Desktop Mobile
Chrome Edge Firefox Internet Explorer Opera Safari WebView Android Chrome Android Firefox for Android Opera Android Safari on IOS Samsung Internet
removeChild
1
12
1
5
7
1.1
1
18
4
10.1
1
1.0

See also

© 2005–2021 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/Node/removeChild