题解 | #dom节点转成json数据#

dom节点转成json数据

http://www.nowcoder.com/practice/0340a0c6d11d4aadba0aef86e6ae723f

递归解析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);
}

全部评论

相关推荐

自由水:这HR已经很好了,多的是已读不回和不读了
点赞 评论 收藏
分享
喜欢喜欢喜欢:这是我见过最长最臭的简历
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务