遍历DOM精简实现

下面用比较精简的代码实现遍历DOM树节点

function travel(node, fn){
    var next = node.firstChild;
    while ((node = next)) {
        fn && fn(node);
        next = node.firstChild || node.nextSibling;
        while (!next && (node = node.parentNode)){
            next = node.nextSibling;
        }
    }
}
//打印出所有的p标签
travel(document.body, function(node){
    if(node.nodeName.toLowerCase() == 'p'){ 
        console.log(p);
    }
});
//模拟getElementsByTagName
function getElementsByTagName(node, tagName){
    var  i = 0,
         result, 
         elements = [], 
         everyTag = !tagName || (tagName === '*');
!everyTag && (tagName = tagName.toLowerCase()); travel(node, function(node){ if(node.nodeType === 1 && everyTag || node.nodeName.toLowerCase() === tagName){ elements[i++] = node; } });
result
= elements.slice(0);//拷贝一份 elements = null;//因travel函数形成一个闭包引用到elements,所以应该将elements设置为null,防止内存泄露 return result; }

 

posted on 2013-10-12 22:35  shiny_bender  阅读(258)  评论(0编辑  收藏  举报

导航