任何一个node节点都可以作为遍历的根(traversal root),然后遍历该节点本身以及后代元素,不能遍历祖先或者兄弟元素,方向可以反转
<div id=”div1”>
<p><b>Hello</b> world!</p><ul>
<li>List item 1</li><li>List item 2</li>
<li>List item 3</li>
</ul>
</div>
使用NodeIterator遍历:
var div = document.getElementById(“div1”);
var iterator = document.createNodeIterator(div, NodeFilter.SHOW_ELEMENT, null, false);
var node = iterator.nextNode();
while (node !== null) {
alert(node.tagName); //output the tag namenode = iterator.nextNode();
}
使用TreeWalker,更为先进的方案:
var div = document.getElementById(“div1”);
var walker = document.createTreeWalker(div, NodeFilter.SHOW_ELEMENT, null, false);
walker.firstChild(); //go to <p>
walker.nextSibling(); //go to <ul>
var node = walker.fi rstChild(); //go to fi rst <li>
while (node !== null) {
alert(node.tagName);node = walker.nextSibling();
}
walker.currentNode = document.body; //change where to start from