Main Page

createDocumentFragment

This sample page replaces the message
“Hello World!”
with
“Hello Universe!”
Note that this code
still uses the
parentNode
property to ensure the correct parent is being manipulated.
Of course, you may want both messages to appear. If you want the new message to come after the old
message, use the
appendChild()
method:
<html>
<head>
<title>appendChild() Example</title>
<script type=”text/javascript”>
function appendMessage() {
var oNewP = document.createElement(“p”);
var oText = document.createTextNode(“Hello Universe! “);
oNewP.appendChild(oText);
document.body.appendChild(oNewP);
}
</script>
</head>
<body onload=”appendMessage()”>
<p>Hello World!</p>
</body>
</html>
If, however, you want the new message to come before the old, use the
insertBefore()
method. This
method accepts two arguments: the new node to add and the node that it should be inserted before. In
this example, the second argument is the
<p />
element containing
“Hello World!”
:
<html>
<head>
<title>insertBefore() Example</title>
<script type=”text/javascript”>
function insertMessage() {
var oNewP = document.createElement(“p”);
var oText = document.createTextNode(“Hello Universe! “);
oNewP.appendChild(oText);
var oOldP = document.getElementsByTagName(“p”)[0];
document.body.insertBefore(oNewP, oOldP);
}
</script>
</head>
<body onload=”insertMessage()”>
<p>Hello World!</p>
</body>
</html>
createDocumentFragment()
As soon as you add nodes to
document.body
(or one of its ancestors), the page is updated to reflect the
changes. This is fine for a small number of changes, as in the previous examples. However, when a large
amount of data has to be added to the
document
, it can be a very slow process if it adds changes one-by-
one. To correct this situation, you can create a document fragment to which you attach all new nodes,
and then add the contents of the document fragment to the
document
.
177
DOM Basics
09_579088 ch06.qxd 3/28/05 11:37 AM Page 177


JavaScript EditorFree JavaScript Editor     Ajax Editor


©