Main Page

DOM Traversal

Creating a cell is done in a similar way — calling
insertCell()
on the
<tr/>
element and passing in the
position in which the cell should be placed. The cell can then be referenced by
oTBody.rows[0].cells[0]
because the cell has been created and inserted into the row in position 0.
Using these properties and methods to create a table makes the code much more logical and readable,
although technically both sets of code are correct.
DOM Traversal
Up until this point, the features discussed have all been part of DOM Level 1. This section introduces
some of the features of DOM Level 2, specifically objects in the DOM Level 2 Traversal and Range speci-
fication relating to traversing a DOM document. These features are only available in Mozilla and
Konqueror/Safari.
NodeIterator
The first object of interest is the
NodeIterator
, which enables you to do a depth-first search of a DOM
tree, which can be useful if you are looking for specific types of information (or elements) in a page. To
understand what the
NodeIterator
does, consider the following HTML page:
<html>
<head>
<title>Example</title>
</head>
<body>
<p>Hello <b>World!</b></p>
</body>
</html>
This page evaluates to the DOM tree represented in Figure 6-2.
When using a
NodeIterator
, it’s possible to start from the
document
element,
<html/>
, and traverse
the entire DOM tree in a systematic way known as a depth-first search. In this method of searching, the
traversal goes as deep as it possibly can from parent to child, to that child’s child, and so on, until it can’t
go any further. Then, the traversal goes back up one level and goes to the next child. For instance, in the
DOM tree shown previously, the traversal first visits
<html/>
, then
<head/>
, then
<title/>
, then the
text node
“Example”
, before going back up to
<body/>
. Figure 6-3 displays the complete path for the
traversal.
The best way to think of a depth-first search is to draw a line that starts from the left of the first node and
follows the outline of the tree. Whenever the line passes a node on its left, the node appears next in the
search (this line is indicated by the thick line in Figure 6-3).
182
Chapter 6
09_579088 ch06.qxd 3/28/05 11:37 AM Page 182


JavaScript EditorFree JavaScript Editor     Ajax Editor


©