// html
<html>
<div>hello</div>
<div>world</div>
<a href=""></a>
</html>
//输出一个数组
const result = [{tag:'div',num: 100}, {tag: 'div',num: 80}];
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div class="hello">
<ul>
<li></li>
<li></li>
<li></li>
</ul>
</div>
<section>
<aside>
</aside>
<p>
<span></span>
<span></span>
<span></span>
<span></span>
</p>
</section>
</body>
<script>
// 方法一
var res = []
var nodelist = document.body.getElementsByTagName('*') // 拿到就是扁平的,不需要递归
var obj = {}
for (let i = 0; i < nodelist.length; i++) {
// localName == tagName.toLowerCase()
if (obj[nodelist[i].localName]) {
obj[nodelist[i].localName] ++
} else {
obj[nodelist[i].localName] = 1
}
}
for (const key in obj) {
res.push({
tag: key,
num: obj[key]
})
}
res.sort((a,b) => (b.num - a.num))
console.log(obj)
console.log(res)
// 方法二 递归
var res1 = []
var obj1 = {}
function count (node) {
var tagName = node.nodeName.toLowerCase()
if (obj1[tagName]) {
obj1[tagName] ++
} else {
obj1[tagName] = 1
}
if (node.children) {
for (let i = 0; i < node.children.length;i++) {
count(node.children[i])
}
}
}
count(document.body)
for (const key in obj1) {
res1.push({
tag: key,
num: obj1[key]
})
}
res1.sort((a,b) => (b.num - a.num))
console.log(obj1)
console.log(res1)
</script>
</html>