Main Page

TreeWalker

</script>
</head>
<body>
<div id=”div1”>
<p>Hello <b>World!</b></p>
<ul>
<li>List item 1</li>
<li>List item 2</li>
<li>List item 3</li>
</ul>
</div>
<textarea rows=”10” cols=”40” id=”text1”></textarea><br />
<input type=”button” value=”Make List” onclick=”makeList()” /> </body>
</html>
This time when the button is clicked, the
<textarea/>
is filled with the following:
UL
LI
LI
LI
Note that both
“P”
and
“B”
have disappeared from the list. This is because filtering out the
<p/>
ele-
ment eliminates it and all its ancestors from the iteration search. Because
<b/>
is a child of
<p/>
, it is
also skipped.
The
NodeIterator
object presents an orderly way of traversing an entire DOM tree (or just part of it)
from top to bottom. However, you may want to traverse a particular area of the tree and then look at a
node’s sibling or child. In that case, you use a
TreeWalker
.
TreeWalker
The
TreeWalker
is like the big brother of
NodeIterator
: It has all the same functionality (with
nextNode()
and
previousNode()
) but with added traversal methods:
?
parentNode()
— travels to the current node’s parent
?
firstChild()
— travels to the first child of the current node
?
lastChild()
— travels to the last child of the current node
?
nextSibling()
— travels to the next sibling of the current node
?
previousSibling()
— travels to the previous sibling of the current node
To start, you can actually use a
TreeWalker
just like a
NodeIterator
by replacing the call to
createNodeIterator()
with a call to
createTreeWalker()
, which accepts the same arguments:
<html>
<head>
<title>TreeWalker Example</title>
<script type=”text/javascript”>
187
DOM Basics
09_579088 ch06.qxd 3/28/05 11:37 AM Page 187


JavaScript EditorFree JavaScript Editor     Ajax Editor


©