题目描述:
上述表达式的输出结果为
['DIV']
['P', 'SPAN', 'P', 'SPAN']
['SPAN', 'SPAN']
直接上代码
let tree = document.querySelector(".a");
function traverseElRoot(elRoot) {const result = [];function traverse(element, level) {if (!result[level]) {result[level] = [];}result[level].push(element.tagName);Array.from(element.children).forEach((child) => {traverse(child, level + 1);});}traverse(elRoot, 0);return result;
}
console.log(traverseElRoot(tree));
输出