# 如何找到当前页面出现次数最多的HTML标签

Issue

欢迎在 Issue 中交流与讨论: Issue 418

Author

回答者: shfshanyue

这是一道前端基础与编程功底具备的面试题:

  • 如果你前端基础强会了解 document.querySelector(*) 能够列出页面内所有标签
  • 如果你编程能力强能够用递归快速实现同等的效果

有三种 API 可以列出页面所有标签:

  1. document.querySelector('*'),标准规范实现
  2. $$('*'),devtools 实现
  3. document.all,非标准规范实现
> document.querySelectorAll('*')
< NodeList(593) [html, head, meta, meta, meta, meta, meta, meta, meta, title, link#favicon, link, link#MainCss, link#mobile-style, link, link, link, script, script, script, script, script, script, script, link, script, link, link, script, input#_w_brink, body, a, div#home, div#header, div#blogTitle, a#lnkBlogLogo, img#blogLogo, h1, a#Header1_HeaderTitle.headermaintitle.HeaderMainTitle, h2, div#navigator, ul#navList, li, a#blog_nav_sitehome.menu, li, a#blog_nav_myhome.menu, li, a#blog_nav_newpost.menu, li, a#blog_nav_contact.menu, li, a#blog_nav_rss.menu, li, a#blog_nav_admin.menu, div.blogStats, span#stats_post_count, span#stats_article_count, span#stats-comment_count, div#main, div#mainContent, div.forFlow, div#post_detail, div#topics, div.post, h1.postTitle, a#cb_post_title_url.postTitle2.vertical-middle, span, div.clear, div.postBody, div#cnblogs_post_body.blogpost-body, p, p, strong, p, p, p, strong, div.cnblogs_code, pre, span, span, span, span, span, p, span, strong, pre, strong, span, strong, br, br, br, div.cnblogs_code, pre, span, span, p, p,]
[099]
[100199]
[200299]
[300399]
[400499]
[500592]
__proto__: NodeList

使用 document.querySelectorAll 实现如下

const maxBy = (list, keyBy) => list.reduce((x, y) => keyBy(x) > keyBy(y) ? x : y)

function getFrequentTag () {
  const tags = [...document.querySelectorAll('*')].map(x => x.tagName).reduce((o, tag) => { 
    o[tag] = o[tag] ? o[tag] + 1 : 1;
    return o
  }, {})
  return maxBy(Object.entries(tags), tag => tag[1])
}

使用 element.children 递归迭代如下 (最终结果多一个 document)

function getAllTags(el = document) {
  const children = Array.from(el.children).reduce((x, y) => [...x, ...getAllTags(y)], [])
  return children
}

// 或者通过 flatMap 实现
function getAllTags(el = document) {
  const children = Array.prototype.flatMap.call(el.children, x => getAllTags(x))
  return [el, ...children]
}

扫码关注公众号全栈成长之路,并发送

即可在关注期间无限制浏览本站全部文章内容

你也可以在文章关于回复公众号扫码解锁全站的技术实现中获得解锁代码,永久解锁本站全部文章

Last Updated: 10/12/2020, 12:24:45 PM