知识点
- 使用
document.documentElement
获取页面的<HTML>
标签 - DOM节点的
children
属性是一个类数组对象,转换为数组的方法 - 数组去重
- 递归
题目
完成getPageTags
函数,判断你的代码所执行的页面用到了哪些标签。
例如,如果页面中:
<html>
<head></head>
<body></body>
<script>...</script>
</html>
那么getPageTags()
则返回数组['html', 'head' 'body', 'script']
(顺序不重要)。
实现
首先,要获得当前元素的根元素,也就是html
,可以通过querySelector
实现,也可以通过document.documentElement
获得
然后我首先想到的是,利用了一个中间数组变量result
,在每次递归时调传递,最后对数组去重即可
const getPageTags = (node = document.documentElement, result = []) => {
if (node && node.tagName) {
result.push(node.tagName)
}
if (node.children && node.children.length > 0) {
[...node.children].forEach(v => getPageTags(v, result))
}
return [...new Set(result)]
};
其实不用传递参数,改用闭包也是可以实现的
另一种方法
能不能不用传递参数,直接通过递归调用实现呢?肯定是可以的,首先就要找到递归的公式:
[当前的tagName].concat(...[子元素的tagName])
那么就可以实现了:
const getPageTags = (node = document.documentElement) => {
if (node.children && node.children.length > 0) {
// 递归找到子元素的标签
const childrenNode = [...node.children].map(v => getPageTags(v));
// 和当前元素的标签结合
const result = [node.tagName].concat(...childrenNode);
// 去重
return [...new Set(result)]
}
// 最基本的节点,返回标签
return node.tagName || ''
};