题解 | #dom节点转成json数据#
dom节点转成json数据
https://www.nowcoder.com/practice/0340a0c6d11d4aadba0aef86e6ae723f
function dom2json() { const container = document.querySelector("#jsContainer"); function createObj (dom) { let obj = { "tag": dom.tagName.toLowerCase(), "attributes": {}, "children": [] } for (let i = 0; i < dom.attributes.length; i++) { const { name, value } = dom.attributes[i]; obj.attributes[name] = value; } for (let i = 0; i < dom.childNodes.length; i++) { if (!dom.childNodes[i].tagName) { if (!dom.childNodes[i].data.trim()) continue; obj.children.push({ "tag": "text", "content": dom.childNodes[i].data.trim() }) } else { obj.children.push(createObj(dom.childNodes[i])) } } return obj; } return createObj(container); }