JavaScript dom节点转成json数据

function dom2json() {
    // 获取到dom对象
    const domBox = document.querySelector("#domBox")
 
 
    function domJson(dom) {
        const obj = {
            tag: getTagName(dom)
        }
        // dom节点为元素element,nodeType节点类型为1
        if (dom.nodeType == 1) {
            const attrs = getTagAttrs(dom)
            if (attrs) obj.attributes = attrs;
            // 筛选出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) {
        // 获取到属性数组
        const attr = Array.from(dom.attributes)
        const obj = {}
        attr.forEach(atr => obj[atr.name] = atr.value)
        return attr.length ? obj : null;
    }
 
    return domJson(domBox)
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值