Main Page

DOM HTML Features

Suppose you want to create ten new paragraphs. Using the methods you learned previously, you write
this code:
var arrText = [“first”, “second”, “third”, “fourth”, “fifth”, “sixth”, “seventh”,
“eighth”, “ninth”, “tenth”];
for (var i=0; i < arrText.length; i++) {
var oP = document.createElement(“p”);
var oText = document.createTextNode(arrText[i]);
oP.appendChild(oText);
document.body.appendChild(oP);}
This code works just fine, the problem is that it’s making ten calls to
document.body.appendChild()
,
which causes a refresh of the page each time. This is where the document fragment is useful:
var arrText = [“first”, “second”, “third”, “fourth”, “fifth”, “sixth”, “seventh”,
“eighth”, “ninth”, “tenth”];
var oFragment = document.createDocumentFragment();
for (var i=0; i < arrText.length; i++) {
var oP = document.createElement(“p”);
var oText = document.createTextNode(arrText[i]);
oP.appendChild(oText);
oFragment.appendChild(oP);
}
document.body.appendChild(oFragment);
In this code, each new
<p />
element is added to the document fragment. Then, the fragment is passed
in as the argument to
appendChild()
. The call to
appendChild()
doesn’t actually append the docu-
ment fragment node itself to the
<body />
element; instead, it just appends the fragment’s child nodes.
You can see the obvious performance gains: One call to
document.body.appendChild()
instead of 10
means only one screen refresh.
DOM HTML Features
The properties and methods of the Core DOM are generic, designed to work with every XML document
in every situation. The properties and methods of the HTML DOM are specific to HTML and make cer-
tain DOM manipulations easier. These include the capability to access attributes as properties in addi-
tion to element-specific properties and methods that can make common tasks, such as building tables,
much more straightforward.
Attributes as properties
For the most part, all attributes are included in HTML DOM elements as properties. For example, sup-
pose you had the following image element:
<img src=”mypicture.jpg” border=”0” />
178
Chapter 6
09_579088 ch06.qxd 3/28/05 11:37 AM Page 178


JavaScript EditorFree JavaScript Editor     Ajax Editor


©