需求:使用js获取页面所有标签及个标签数量
代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
window.onload = function () {
let elements = document.getElementsByTagName('*');
elements = Array.from(elements).map((item)=>{
return item.nodeName.toLowerCase();
}).sort();
function qc(arr) {
let Ele = [...new Set(arr)];
let obj = {};
let results = [];
arr.forEach(v=>{
if(obj[v]){
obj[v]++;
}else {
obj[v]=1;
}
})
Ele.forEach(v=>{
results.push({
nodeName: v,
num: obj[v]
})
})
return results;
}
function compare(num,attr){
return function(o1,o2){
if(attr === 'asc'){
return o1[num] < o2[num] ? -1 : 1;
}else {
return o1[num] > o2[num] ? -1 : 1;
}
}
}
let res = qc(elements).sort(compare('num','desc'));
console.log(res);
}
</script>
</head>
<body>
<div>哈哈</div>
<span>11</span>
<div>22</div>
</body>
</html>