↑
Main Page
removeChild
You’re not done quite yet. You have created the element and text node and attached them to each other,
but the element still doesn’t have a spot in the document. To actually be visible, the element must be
attached either to the
document.body
element or one of its children. Once again, you can use the
appendChild()
method for this:
document.body.appendChild(oP);
To put all this into a sample you can run, just create a function containing each of these steps and call it
when the page is loaded by using the
onload
event handler (events will be covered in more detail in the
Chapter 9, “All About Events”):
<html>
<head>
<title>createElement() Example</title>
<script type=”text/javascript”>
function createMessage() {
var oP = document.createElement(“p”);
var oText = document.createTextNode(“Hello World! “);
oP.appendChild(oText);
document.body.appendChild(oP);
}
</script>
</head>
<body onload=”createMessage()”>
</body>
</html>
When you run this code, the message
“Hello World!”
is displayed as if it were part of the HTML doc-
ument all along.
removeChild(), replaceChild(), and insertBefore()
Naturally, if you can add a node you can also remove a node, which is where the
removeChild()
method comes in. This method accepts one argument, the node to remove, and then returns that node as
the function value. So if, for instance, you start out with a page already containing the
“Hello World!”
message and you wanted to remove it, you can use the method like this:
<html>
<head>
<title>removeChild() Example</title>
<script type=”text/javascript”>
function removeMessage() {
var oP = document.body.getElementsByTagName(“p”)[0];
At this point, it’s prudent to point out that all DOM manipulation must occur after
the page has fully loaded. It isn’t possible to insert code while a page is loading to
work with the DOM because the DOM tree isn’t fully constructed until the page has
been completely downloaded to the client machine. For this reason, all code must be
executed using the
onload
event handler.
175
DOM Basics
09_579088 ch06.qxd 3/28/05 11:37 AM Page 175
Free JavaScript Editor
Ajax Editor
©
→