Main Page

DOM Traversal

Creating a cell is done in a similar way — calling
on the
element and passing in the
position in which the cell should be placed. The cell can then be referenced by
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
The first object of interest is the
, 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
does, consider the following HTML page:
<p>Hello <b>World!</b></p>
This page evaluates to the DOM tree represented in Figure 6-2.
When using a
, it’s possible to start from the
, 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
, then
, then
, then the
text node
, before going back up to
. Figure 6-3 displays the complete path for the
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).
Chapter 6
09_579088 ch06.qxd 3/28/05 11:37 AM Page 182

JavaScript EditorFree JavaScript Editor     Ajax Editor