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

dom节点转成json数据

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

function dom2json() {
    //获取到dom对象
    const jsContainer = document.querySelector("#jsContainer")

    console.log(jsContainer)
    console.log(typeof jsContainer)
    console.log(jsContainer.nodeName)  //DIV
    console.log(jsContainer.nodeName.toLocaleLowerCase())
    console.log(jsContainer.nodeType)  //nodeType:1  代表该节点为元素节点
    console.log(jsContainer.attributes)
    console.log(Array.from(jsContainer.attributes))
    console.log(jsContainer.childNodes)
    console.log(typeof jsContainer.childNodes)  //NodeList  object


    function domJson(dom) {
        var obj = {
            tag: getTagName(dom)
        }
        //dom节点为元素element,nodeType节点类型为1
        if (dom.nodeType == 1) {
            var attrs = getTagAttrs(dom)
            if (attrs) obj.attributes = attrs;
            console.log(dom.children)
            //筛选出nodeType不为3且文本内容不为空的子DOM节点,并进行递归
            obj.children = Array.from(dom.childNodes).filter(child => {
                return !(child.nodeType == 3 && !child.textContent.trim())
            }).map(child => domJson(child))
            return obj
        }
        //dom节点为文本类型, nodeType节点类型为3
        if (dom.nodeType == 3) {
            obj.content = texthandle(dom.textContent)
            return obj
        }
    }

    //去除空白符
    function texthandle(str) {
        return str.replace(/\s/g, '')
    }

    //获取到节点的标签名,注意需要转换为小写
    function getTagName(dom) {
        return dom.nodeName.toLocaleLowerCase().replace('#', '')
    }

    //获取节点的属性对象
    function getTagAttrs(dom) {
        //获取到属性数组
        var attr = Array.from(dom.attributes)
        var obj = {}
        attr.forEach(atr => obj[atr.name] = atr.value)
        return attr.length ? obj : null;
    }

    return domJson(jsContainer)
}

dom2json()
console.log(dom2json())
全部评论

相关推荐

今天 19:58
门头沟学院 C++
点赞 评论 收藏
分享
见见123:简历没有啥问题,是这个社会有问题。因为你刚毕业,没有工作经历,现在企业都不要没有工作经历的。社会病了。
点赞 评论 收藏
分享
白火同学:能。我当初应届沟通了1200,收简历50,面试10左右吧,加油投吧
点赞 评论 收藏
分享
评论
2
1
分享

创作者周榜

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