console
/*
作者:TangPoems
链接:https://www.nowcoder.com/discuss/871077?type=post&order=create&pos=&page=1&ncTraceId=&channel=-1&source_id=search_post_nctrack&subType=2&gio_id=4B11D26016AC8D56CAC57B6E316F3069-1648730048097
来源:牛客网
{
tag:'DIV',
children:[
{tag:'SPAN'
children:[{tag:'DIV',
children:[]},
{tag:'DIV',
children:[]}
]},
{tag:'SPAN'
children:[{tag:'DIV',
children:[]},
{tag:'DIV',
children:[]}
]}
]
}
*/
function getTree (root) {
const obj = Object.create(null)
obj.tag = root && (root.tagName || '')
obj.children = []
for (let i = 0; i < root.children.length; i++) {
obj.children.push(getTree(root.children[i]))
}
return obj
}
console.log(getTree(document.querySelectorAll('div')[0]))
<div>
<span>
<div></div>
<div></div>
</span>
<span>
<div></div>
<div></div>
</span>
</div>