Skip to content

遍历DOM节点,根据id返回对应dom树

    <div id="box">
        <ul id="uls">
            <li>1</li>
            <li>2</li>
            <li>3</li>
        </ul>
        <p id="p1">
            <span>ppppp</span>
        </p>
    </div>

方式一:深度优先,递归操作实现

    function findAllDom(parentNode, id) {
        if (parentNode) {
            let target = null;
            let children = Array.from(parentNode.children)
            if (parentNode.id == id) {
                return parentNode
            }
            for (let index = 0; index < children.length; index++) {
                target = findAllDom(children[index], id)
                if (target) return target
            }
        }
    }
    let myBox = document.getElementById("box");
    console.log(findAllDom(myBox, 'p1'))

方式二:深度优先 ===》使用栈(非递归操作)

    function allDom(parentNode, id) {
        if (!parentNode) {
            return null
        }
        if (parentNode.id == id) {
            return parentNode
        }
        let children = parentNode.children;
        let stack = [];
        for (let index = children.length; index > 0; index--) {
            stack.push(children[index - 1])
        }
        while (stack.length) {
            let node = stack.pop();
            if (node.id == id) {
                return node
            } else {
                if (node.children.length > 0) {
                    stack = Array.from(node.children).concat(stack)
                }
            }
        }
        return stack
    }
    let myBox = document.getElementById("box");
    console.log(allDom(myBox, 'uls'))