Syntax
js
removeChild(child)
Parameters
Return value
The removed child node.
Exceptions
NotFoundErrorDOMException-
Thrown if the
childis not a child of the node. TypeError-
Thrown if the
childisnull.
Examples
Simple examples
Given this HTML:
html
<div id="parent">
<div id="child"></div>
</div>
To remove a specified element when knowing its parent node:
js
const parent = document.getElementById("parent");
const child = document.getElementById("child");
const throwawayNode = parent.removeChild(child);
To remove a specified element without having to specify its parent node:
js
const node = document.getElementById("child");
if (node.parentNode) {
node.parentNode.removeChild(node);
}
To remove all children from an element:
js
const element = document.getElementById("idOfParent");
while (element.firstChild) {
element.removeChild(element.firstChild);
}
Causing a TypeError
html
<!--Sample HTML code-->
<div id="parent"></div>
js
const parent = document.getElementById("parent");
const child = document.getElementById("child");
// Throws Uncaught TypeError
const garbage = parent.removeChild(child);
Causing a NotFoundError
html
<!--Sample HTML code-->
<div id="parent">
<div id="child"></div>
</div>
js
const parent = document.getElementById("parent");
const child = document.getElementById("child");
// This first call correctly removes the node
const garbage = parent.removeChild(child);
// Second call throws NotFoundError
parent.removeChild(child);
Specifications
| Specification |
|---|
| DOM # dom-node-removechild |