HTML DOM Element removeChild()
Examples
Remove the first element from a list:
list.removeChild(list.firstElementChild);
Before:
- Coffee
- Tea
- Milk
After:
- Tea
- Milk
If a list has child nodes, remove the first (index 0):
if (list.hasChildNodes()) {
list.removeChild(list.children[0]);
}
Remove all child nodes from a list:
while (list.hasChildNodes()) {
list.removeChild(list.firstChild);
}
More examples below.
Description
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
Parameters
The node (element) to remove.
Return Value
null
if the child does not exist.
More Examples
Example
Remove an element from its parent, and insert it again:
function removeLi() {
element.parentNode.removeChild(element);
}
function appendLi() {
const list = document.getElementById("myList");
list.appendChild(element);
}
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:
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);
}
Browser Support
element.removeChild()
is a DOM Level 1 (1998) feature.
It is fully supported in all browsers:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | 9-11 |