MDN self-hosted library · e01.org

Node: removeChild() method

Runnable notebook: every JavaScript, HTML and CSS example on this page executes in a sandboxed local frame. Nothing leaves the browser.

html
<div id="parent">
  <div id="child"></div>
</div>
js
const parent = document.getElementById("parent");
const child = document.getElementById("child");
const throwawayNode = parent.removeChild(child);
js
const node = document.getElementById("child");
if (node.parentNode) {
  node.parentNode.removeChild(node);
}
js
const element = document.getElementById("idOfParent");
while (element.firstChild) {
  element.removeChild(element.firstChild);
}
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);
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);