↑
Main Page
Detecting DOM Conformance
var oOutput = document.getElementById(“text1”);
walker.firstChild(); //go to <p>
walker.nextSibling(); //go to <ul>
var oNode = walker.firstChild(); //go to first <li>
while (oNode) {
oOutput.value += oNode.tagName + “\n”;
oNode = walker.nextSibling();
}
}
</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>
In this example, the
TreeWalker
is created and immediately
firstChild()
is called, which points the
walker at the
<p/>
element (because
<p/>
is the first child of
div1
). When
nextSibling()
is called on
the next line, the walker goes to
<ul/>
, which is the next sibling of
<p/>
. Then,
firstChild()
is called
to return the first
<li/>
element under
<ul/>
. After it is inside the loop, the
nextSibling()
method is
used to iterate through the rest of the
<li/>
elements.
When you click the button, the output is the following:
LI
LI
LI
The bottom line is that the
TreeWalker
is much more useful when you have an idea about the structure
of the DOM tree you will be traversing, whereas a
NodeIterator
is much more practical when you
don’t know the structure.
Detecting DOM Conformance
As you can tell, there’s a lot to the DOM. For this reason, you have a method to determine which parts
of the DOM are supported by any given implementation. The object is named, ironically enough,
implementation
.
189
DOM Basics
09_579088 ch06.qxd 3/28/05 11:37 AM Page 189
Free JavaScript Editor
Ajax Editor
©
→