浙江省高等学校教师教育理论培训

微信搜索“教师资格证岗前培训”小程序

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

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:
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:
1.findNodeByTag(myDOMobj, "img");
posted on 2012-12-17 00:17  lexus  阅读(192)  评论(0编辑  收藏  举报