您的位置:首页 > Web前端

San Francisco Bay Area Professional Blog: Traverse/walk DOM tree recursively

2012-12-17 00:17 281 查看
San Francisco Bay Area Professional Blog: Traverse/walk DOM tree recursively

Traverse/walk DOM tree recursively

Task definition: You have a DOM tree (startNode which can be the whole document), and need to find first specific tag in this tree.

Here is the recursion function to do this:
view sourceprint?
1.
function
findNodeByTag(startNode, tagName) {
2.
if
(startNode.nodeName.toLowerCase() == tagName.toLowerCase())
return
startNode;
3.
var
childList = startNode.childNodes;
4.
for
(
var
i=0; i<childList.length; i++) {
5.
return
findNodeByTag(childList[i], tagName);
6.
}
7.
return
null
;
8.
}

And you call it:
view sourceprint?
1.
findNodeByTag(myDOMobj,
"img"
);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: