递归解析dom节点,简洁带注释版js代码


function dom2json() {
    const jsContainer = document.getElementById('jsContainer');
    function dfp(root) {
        // 递归结束条件,遇到text,空text返回null,其他返回对象
        if (root.nodeType === 3) {
            if (root.textContent.trim().length === 0) {
                return null;
            }
            return {
                tag: 'text',
                content: root.textContent.trim()
            };
        }
        // 定义返回的obj
        const obj = {
            tag: root.nodeName.toLocaleLowerCase(),
            attributes: {},
            children: []
        }
        // 解析属性,不能用for of
        for (let i = 0; i < root.attributes.length; i++) {
            const {name, value} = root.attributes[0];
            obj.attributes[name] = value;
        }
        // 解析children,不能用for of
        for (let i = 0; i < root.childNodes.length; i++) {
            const childObj = dfp(root.childNodes[i]);
            if (childObj === null) {
                continue;
            }
            obj.children.push(childObj);
        }
        return obj;
    }
    return dfp(jsContainer);
}