HTML DOM removeChild() Method
Element Object
Example
Remove the first <li> element from a list:
var list = document.getElementById("myList"); // Get
the <ul> element with id="myList"
list.removeChild(list.childNodes[0]);
// Remove <ul>'s first child node (index 0)
Before removing:
After removing:
Try it yourself »
More "Try it Yourself" examples below.
Definition and Usage
The removeChild() method removes a specified child node of the specified element.
Returns the removed node as a Node object, or null if the node does not exist.
Note: The removed child node is no longer part of the DOM.
However, with the reference returned by this method, it is possible to insert
the removed child to an element at a later time (See "More Examples").
Tip: Use the appendChild() or
insertBefore() method to
insert the removed node into the same document. To insert it to another
document, use the document.adoptNode() or
document.importNode() method.
Browser Support
Method |
|
|
|
|
|
removeChild() |
Yes |
Yes |
Yes |
Yes |
Yes |
Syntax
Parameter Values
Parameter |
Type |
Description |
node |
Node object |
Required. The node object you want to remove |
Technical Details
Return Value: |
A Node object, representing the removed node, or null if the
node does not exist |
DOM Version |
Core Level 1 Node Object |
More Examples
Example
Find out if a list has any child nodes. If so,
remove its first child node (index 0):
// Get the <ul> element with id="myList"
var list =
document.getElementById("myList");
// If the <ul> element has any
child nodes, remove its first child node
if (list.hasChildNodes()) {
list.removeChild(list.childNodes[0]);
}
Before removing:
Before removing:
Try it yourself »
Example
Remove all child nodes of a list:
// Get the <ul> element with id="myList"
var list = document.getElementById("myList");
// As long as <ul> has a child node, remove it
while
(list.hasChildNodes()) {
list.removeChild(list.firstChild);
}
Before removing:
After removing:
Try it yourself »
Example
Remove a <li> element with id="myLI" from
its parent element (without specifying its
parent node):
var item = document.getElementById("myLI");
item.parentNode.removeChild(item);
Before removing:
After removing:
Try it yourself »
Example
Remove a <li> element from its parent, and insert it again:
var item = document.getElementById("myLI");
function removeLi() {
item.parentNode.removeChild(item);
}
function appendLi() {
var list = document.getElementById("myList");
list.appendChild(item);
}
Try it yourself »
Example
Remove a <span> element from its parent and insert it to
an <h1> element in another document:
var child = document.getElementById("mySpan");
function removeLi() {
child.parentNode.removeChild(child);
}
function myFunction() {
var frame = document.getElementsByTagName("IFRAME")[0]
var h = frame.contentWindow.document.getElementsByTagName("H1")[0];
var x = document.adoptNode(child);
h.appendChild(x);
}
Try it yourself »
Element Object
Color Picker