Remove the first element from a list:
const list = document.getElementById("myList");
list.removeChild(list.firstElementChild);
Before:
After:
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.
The removeChild()
method removes an element's child.
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").
element.removeChild(
node)
node.removeChild(
node)
Parameter | Description |
node | Required. The node (element) to remove. |
Type | Description |
Node | The removed node (element).null if the child does not exist. |
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 »
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.
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 »
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 |
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!