removeChild
In this chapter you will learn:
Remove a child
The removeChild()
method removes a node.
This method accepts a single argument,
which is the node to remove.
The removed node is returned:
The following code removes first child from its parent.
<!DOCTYPE html><!--from j av a 2 s . c o m-->
<html>
<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 the last node
The following code removes the last child.
<!DOCTYPE html><!--from j a va 2s.co m-->
<html>
<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.
Next chapter...
What you will learn in the next chapter: