题解 | #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);
}

全部评论

相关推荐

🎓学历背景:末二本+北邮硕想找段日常&nbsp;是简历写的有问题吗&nbsp;目前有家100-499的小厂过了,但大厂现在一个都没面过,官网投递一直在筛简历
牛客44176770...:我也28届,也是投了一个多月,四月底投的,面了6.7场,有个大厂,没结果应该是挂了,有三个小厂面试的很顺利,结果没下文了,互联网我恨你!这五月我时间都在投简历和改简历上了,结果没啥收获,算法也没刷,因为约的面试都没有算法索性就只看项目和八股唉,真的好累啊
我的简历长这样
点赞 评论 收藏
分享
04-24 18:13
南京大学 Java
不吃酸菜血肠:看力竭了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务