Main Page


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
element or one of its children. Once again, you can use the
method for this:
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
event handler (events will be covered in more detail in the
Chapter 9, “All About Events”):
<title>createElement() Example</title>
<script type=”text/javascript”>
function createMessage() {
var oP = document.createElement(“p”);
var oText = document.createTextNode(“Hello World! “);
<body onload=”createMessage()”>
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
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:
<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
event handler.
DOM Basics
09_579088 ch06.qxd 3/28/05 11:37 AM Page 175

JavaScript EditorFree JavaScript Editor     Ajax Editor