removeChild
The removeChild() method removes a node. This method accepts a single argument, which is the node to remove. The removed node is returned:
remove first child
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
</head>
<body>
<div id="div1">
<ul>
<li>List item 1</li>
<li>List item 2</li>
<li>List item 3</li>
</ul>
</div>
<p id="p1">Hello <b>World!</b></p>
<script type="text/javascript">
var div = document.getElementById("div1");
var p = document.getElementById("p1");
var formerFirstChild = div.removeChild(div.firstChild);
document.writeln(formerFirstChild);
</script>
</body>
</html>
remove last child
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
</head>
<body>
<div id="div1">
<ul>
<li>List item 1</li>
<li>List item 2</li>
<li>List item 3</li>
</ul>
</div>
<p id="p1">Hello <b>World!</b></p>
<script type="text/javascript">
var div = document.getElementById("div1");
var p = document.getElementById("p1");
var formerLastChild = div.removeChild(div.lastChild);
document.writeln(formerLastChild);
</script>
</body>
</html>
A node removed via removeChild() is still owned by the document but doesn't have a specific location in the document.
Home
JavaScript Book
DOM
JavaScript Book
DOM
DOM Model:
- Document Object Model
- nodeName and nodeValue Properties
- Node Relationships:childNodes
- parentNode
- previousSibling and nextSibling properties
- lastChild and firstChild
- appendChild() adds a node to the end of the childNodes list
- insertBefore()
- ownerDocument property
- removeChild
- replaceChild()
- Working with Text
- Check the length of NodeList
- Convert NodeList to an Array
- html tag and its cooresponding JavaScript class