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

dom节点转成json数据

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

图片说明

function dom2json() {
            const jsContainer = document.querySelector("#jsContainer")

            function domJson(dom) {
                var obj = {
                    tag: getTagName(dom)
                }
                if (dom.nodeType == 1) {
                    var attrs = getTagAttrs(dom)
                    if (attrs) obj.attributes = attrs;
                    console.log(dom.children)
                    obj.children = Array.from(dom.childNodes).filter(child => {
                        return !(child.nodeType == 3 && !child.textContent.trim())
                    }).map(child => domJson(child))
                    return obj
                }
                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)
        }
全部评论
用楼主的代码跑一下子就可以了,但是用自己的死活不行,我对着看没有问题啊,在本地跑也是没问题的....
点赞
送花
回复
分享
发布于 2021-08-23 13:23

相关推荐

2 收藏 评论
分享
牛客网
牛客企业服务