题解 | #dom节点转成json数据#
dom节点转成json数据
http://www.nowcoder.com/practice/0340a0c6d11d4aadba0aef86e6ae723f
function dom2json() { let root = document.getElementById('jsContainer'); return JSON.parse(JSON.stringify(analysisDom(root))) } function analysisDom(dom) { let templete; if (dom.nodeType == 1) { templete = { tag: '', attributes: {}, children: [] }; templete.tag = dom.localName; let len = dom.attributes.length; for (let i = 0; i < len; i++) { templete.attributes[dom.attributes.item(i).nodeName] = dom.getAttribute(dom.attributes.item(i).nodeName); }; let cLen = dom.childNodes.length if (cLen) { for (let i = 0; i < cLen; i++) { if(analysisDom(dom.childNodes[i])){ templete.children.push(analysisDom(dom.childNodes[i])) } } } } else if (dom.nodeType == 3) { let data = dom.textContent.trim(); if (data) { templete = { tag: 'text', content: data } } } return templete }