Main Page

getElementsByTagName

document.body.removeChild(oP);
}
</script>
</head>
<body onload=”removeMessage()”>
<p>Hello World!</p>
</body>
</html>
When this page is loaded, it displays a blank screen because the message is removed even before you
have a chance to see it. Although this works, it’s always better to use a node’s
parentNode
property to
make sure you are accessing its real parent:
<html>
<head>
<title>removeChild() Example</title>
<script type=”text/javascript”>
function removeMessage() {
var oP = document.body.getElementsByTagName(“p”)[0];
oP.parentNode.removeChild(oP);
}
</script>
</head>
<body onload=”replaceMessage()”>
<p>Hello World!</p>
</body>
</html>
But what if you want to replace this message with a new one? In that case, you can use the
replaceChild()
method.
The
replaceChild()
method takes two arguments: the node to add and the node to replace. In this
case, you create a new element with a new message and replace the
<p />
element with the
“Hello
World!”
message.
<html>
<head>
<title>replaceChild() Example</title>
<script type=”text/javascript”>
function replaceMessage() {
var oNewP = document.createElement(“p”);
var oText = document.createTextNode(“Hello Universe! “);
oNewP.appendChild(oText);
var oOldP = document.body.getElementsByTagName(“p”)[0];
oOldP.parentNode.replaceChild(oNewP, oOldP);
}
</script>
</head>
<body onload=”replaceMessage()”>
<p>Hello World!</p>
</body>
</html>
176
Chapter 6
09_579088 ch06.qxd 3/28/05 11:37 AM Page 176


JavaScript EditorFree JavaScript Editor     Ajax Editor


©