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;
}
const domTrans = (dom) => {
let tree = [];
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);
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'))
)