使用js将dom对象转换为js对象

1 篇文章 0 订阅
// 获取元素的属性,输出对象,如果没有属性输出null
    const getAttribute = (dom) => {
        let attributes = {};
        let empty = true;
        Array.from(dom.attributes).map(item => {
            attributes[item.nodeName] = item.nodeValue;
            empty = false;
        })
        return empty ? null : attributes;
    }

    // 将dom转为js-dom
    const domTrans = (dom) => {
        // 总dom树
        let tree = [];

        // 递归, node = 当前的节点,dataNode = 数据插入的节点
        const loop = (node, dataNode) => {
            // 当前节点的模板
            let temp = {
                type: node.nodeType
            }

            // 如果是文本节点 或 单标签节点
            if (temp.type == 3 && node.nodeValue.match(/\S/)) {
                temp['content'] = node.nodeValue;
                temp['tag'] = node.nodeName;
                dataNode.push(temp);
            }

            // 元素节点
            if (temp.type == 1) {
                let attributes = getAttribute(node);

                // 如果没有属性,不添加 attributes
                if (attributes) temp['attributes'] = attributes;

                // 当前节点下只有文本 或 单标签节点
                if (node.childNodes.length <= 1) {
                    temp['content'] = node.innerHTML;
                    temp['tag'] = node.nodeName.toLowerCase();
                }

                // 当前节点下还有子节点
                if (node.childNodes.length > 1) {
                    temp['children'] = [];
                    temp['tag'] = node.nodeName.toLowerCase();
                    for (let i = 0; i < node.childNodes.length; i++) {
                        loop(node.childNodes[i], temp.children);
                    }
                }
                dataNode.push(temp);
            }

        }
        loop(dom, tree);
        return tree[0].children;
    }

    console.log(
        domTrans(document.querySelector('#app'))
    )
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值