题解 | #dom节点转成json数据#
dom节点转成json数据
http://www.nowcoder.com/practice/0340a0c6d11d4aadba0aef86e6ae723f
function dom2json() { //获取到dom对象 const jsContainer = document.querySelector("#jsContainer") console.log(jsContainer) console.log(typeof jsContainer) console.log(jsContainer.nodeName) //DIV console.log(jsContainer.nodeName.toLocaleLowerCase()) console.log(jsContainer.nodeType) //nodeType:1 代表该节点为元素节点 console.log(jsContainer.attributes) console.log(Array.from(jsContainer.attributes)) console.log(jsContainer.childNodes) console.log(typeof jsContainer.childNodes) //NodeList object function domJson(dom) { var obj = { tag: getTagName(dom) } //dom节点为元素element,nodeType节点类型为1 if (dom.nodeType == 1) { var attrs = getTagAttrs(dom) if (attrs) obj.attributes = attrs; console.log(dom.children) //筛选出nodeType不为3且文本内容不为空的子DOM节点,并进行递归 obj.children = Array.from(dom.childNodes).filter(child => { return !(child.nodeType == 3 && !child.textContent.trim()) }).map(child => domJson(child)) return obj } //dom节点为文本类型, nodeType节点类型为3 if (dom.nodeType == 3) { obj.content = texthandle(dom.textContent) return obj } } //去除空白符 function texthandle(str) { return str.replace(/\s/g, '') } //获取到节点的标签名,注意需要转换为小写 function getTagName(dom) { return dom.nodeName.toLocaleLowerCase().replace('#', '') } //获取节点的属性对象 function getTagAttrs(dom) { //获取到属性数组 var attr = Array.from(dom.attributes) var obj = {} attr.forEach(atr => obj[atr.name] = atr.value) return attr.length ? obj : null; } return domJson(jsContainer) } dom2json() console.log(dom2json())