const getAttr = (node) => {
const attribute = {};
if (node.attributes?.length && node.nodeType === 1) {
const attributes = { ...node.attributes };
for (const key in attributes) {
let k = attributes[key].nodeName;
let v = attributes[key].nodeValue;
Object.assign(attribute, { [k]: v });
}
return attribute;
} else {
return null;
}
};
function dom2json(node) {
node.obj = {};
const { obj } = node;
if (node.nodeType === 1) {
// 非文本节点
obj.tag = node.tagName.toLowerCase();
}
if (node.nodeType === 3 && node.data.trim() !== "") {
// 文本节点
obj.tag = "text";
obj.content = node.data.trim();
}
if (getAttr(node)) {
obj.attributes = getAttr(node);
}
const newArrNode = Array.from(node.childNodes).filter(
(cnode) =>
cnode.nodeType === 1 ||
(cnode.nodeType === 3 && cnode.data.trim() !== "")
);
if (node.childNodes && newArrNode.length) {
obj.children = [];
// 符合情况的子节点
newArrNode.forEach((cnode) => {
obj.children.push(dom2json(cnode));
});
}
return obj;
}
let p = dom2json(document.querySelector("#jsContainer"));
console.log(JSON.stringify(p));