HTML and CSS Reference
In-Depth Information
FORMAT
removeChild(referenceToChild)
EXAMPLE
parentDiv1.removeChild(div2);
EXAMPLE 15.15
<html>
<head><title>Removing a Child with the DOM</title>
<script type="text/javascript">
1
function removeDiv() {
2
var divMid = document.body.getElementsByTagName("div")[1];
3
divMid.parentNode.removeChild(divMid);
// Remove the middle div
// alert((document.body.getElementsByTagName("div")).length
//
+ " divs left"); prints 2
}
</script>
</head>
<body onload="removeDiv() ">
4
<div>this is div1</div>
5
<div>this is div2</div>
6
<div>this is div3</div>
</body>
</html>
EXPLANATION
1
The function called removeDiv() will remove a div element from the DOM tree.
2
The getElementsByTagName() method returns a reference to the second div tag in
the document. The [1] index is applied to the <div> reference returned by getEle-
mentsByTagName() , and retrieves the second div. [0] would be the first div in the
list of < div > tags.
3
Using the reference to the second <div> , we go to the parent < div> and remove its
child, the second div (see Figure 15.27).
4
Three div s are defined in this document.
Search WWH ::




Custom Search