当前页面标签top3

14 阅读1分钟

统计代码所在当前页面中,使用的 HTML 标签里,出现频率最高的 top3 并输出

function getTop3Tags() {
  const allElements = document.getElementsByTagName('*');
  const tagCount = {};
  
  // 统计标签
  for (let el of allElements) {
    const tagName = el.tagName.toLowerCase();
    tagCount[tagName] = (tagCount[tagName] || 0) + 1;
  }
  
  // 排序并取前3
  const top3 = Object.entries(tagCount)
    .sort((a, b) => b[1] - a[1])
    .slice(0, 3);
  
  console.log('Top 3 标签:', top3);
  return top3;
}