function dom2json() {
let dom = document.getElementById("jsContainer");
function getJsonObj(node) {
let obj = {};
obj.tag = node.nodeName.toLowerCase().replace("#", "");
if (node.nodeType == 1) {
obj.attributes = {};
let attr = Array.from(node.attributes);
if (attr.length) {
for (let item of attr) {
let { name, value } = item;
obj.attributes[name] = value;
}
}
// 筛选出nodeType不为3或文本内容不为空的子DOM节点
let childList = Array.from(node.childNodes).filter((item) => {
return item.nodeType != 3 || item.textContent.trim();
});
obj.children = [];
if (childList) {
for (let cur of childList) {
let temp = getJsonObj(cur);
obj.children.push(temp);
}
}
}
if (node.nodeType == 3) {
obj.content = node.textContent.replace(/\s/g, "");
}
return obj;
}
return getJsonObj(dom);
}