其他分享
首页 > 其他分享> > 遍历dom

遍历dom

作者:互联网

遍历的两种实现:
1.深度优先遍历:

    const seekDFS=function(rootNode){
        let nodes=[];
        const search=(rootNode)=>{
            if(rootNode.nodeType===1){
                nodes.push(rootNode);
                let children=rootNode.childNodes;
                if(children){
                    for(let i=0;i<children.length;i++){
                        if(children[i].nodeType==1){
                            search(children[i]);
                        }
                    }
                }
            }
        }
        search(rootNode);
        return nodes;
    }

2.广度优先遍历:

    const seekBFS=function(rootNode){
        let stack=[];
        let nodes=[];
        if(rootNode.nodeType==1){
            stack.push(rootNode);
            while(stack.length){
                let item=stack.pop();
                nodes.push(item);
                let children=item.childNodes;
                for(let i=0;i<children.length;i++){
                    if(children[i].nodeType==1){
                        stack.push(children[i]);
                    }
                }
            }
        }
        return nodes;
    }

这两种算法在的意义:
1.遍历dom节点,框架中常用到;
2.实现拷贝

标签:遍历,dom,children,rootNode,let,nodes,stack
来源: https://www.cnblogs.com/maoBable/p/11207794.html