HTML DOM Element removeChild()
Examples
Remove the first element from a list:
const list = document.getElementById("myList");
list.removeChild(list.firstElementChild);
Before:
- Coffee
- Tea
- Milk
After:
- Tea
- Milk
If a list has child nodes, remove the first (index 0):
const list = document.getElementById("myList");
if (list.hasChildNodes()) {
list.removeChild(list.children[0]);
}
Try it Yourself »
Remove all child nodes from a list:
const list = document.getElementById("myList");
while (list.hasChildNodes()) {
list.removeChild(list.firstChild);
}
Try it Yourself »
More examples below.
Definition and Usage
The removeChild()
method removes an element's child.
Note
The child is removed from the Document Object Model (the DOM).
However, the returned node can be modified and inserted back into the DOM (See "More Examples").
See Also:
Syntax
element.removeChild(node)
or
node.removeChild(node)
Parameters
Parameter | Description |
node | Required. The node (element) to remove. |
Return Value
Type | Description |
Node | The removed node (element).null if the child does not exist. |
More Examples
Example
Remove an element from its parent, and 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 »
Note
Use appendChild() or insertBefore() to insert a removed node into the same document.
Use document.adoptNode() or document.importNode() to insert it into another document.
Example
Remove an element from its parent and insert 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 »
Browser Support
element.removeChild()
is a DOM Level 1 (1998) feature.
It is fully supported in all browsers:
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | 9-11 | Yes | Yes | Yes | Yes |