TreeWalker
-创建
document.createTreeWalker(root,what_to_show, filter, if_expand_entity_references)
参考网址:https://developer.mozilla.org/zh-CN/docs/Web/API/TreeWalker
Code Example:
var treeWalker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
while (treeWalker.nextNode()) {
handle(treeWalker.currentNode);
}
function handle(node){
If (node.nodeType==3)// text node
{
//do sth.
}
else If (node.nodeType==1)// element node
{
//do sth.
}
}
Recursive Way
Code example:
遍历并处理所有文本节点
function tranverse_tree(node){
if (current = node.firstChild) {
do {
next = current.nextSibling;
traverse_child_nodes(current,node);
} while (current = next) ;
}
}
function traverse_child_node(node, root){
if (node.nodeType==3)// text node
{
//do sth.
}
else If (node.nodeType==1)// element node
{
// skip some elements
var arr = ["STYLE", "COMMANDSET", "IMG", "NOSCRIPT", "SCRIPT"];
if (arr.Exists(node.nodeName)) // Exists function is self-defined here.
return ;
// keep recursive traverse the sub tree.
var current, next;
if (current = node.firstChild) {
do {
next = current.nextSibling;
traverse_child_node(current,root);
} while (current = next);
}
}
}
Handle Embedded Iframes
当DOM tree中嵌入了Iframe节点时,需要在遍历过程中对其进行特别处理
Iframe是nodetype =1的其中一种情况,同时我理解的就是Iframe加载的也是一颗DOM tree.
So add code to above example:
if (node.nodeType === 1) {
//HANDLE iframe node
if (["IFRAME"].Exists(node.nodeName)) {
tranverse_tree(node.contentDocument.body);
return;
}
…….
}