溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

如何找到當前頁面中出現次數最多的HTML標簽

發(fā)布時間:2021-10-12 15:52:23 來源:億速云 閱讀:131 作者:柒染 欄目:大數據

這篇文章給大家介紹如何找到當前頁面中出現次數最多的HTML標簽,內容非常詳細,感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。

這是一道前端基礎與編程功底具備的面試題:如果你前端基礎強會了解 document.querySelector(*) 能夠列出頁面內所有標簽,如果你編程能力強能夠用遞歸快速實現同等的效果

> 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, h2, a#Header1_HeaderTitle.headermaintitle.HeaderMainTitle, h3, 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, h2.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, …]
[0 … 99]
[100 … 199]
[200 … 299]
[300 … 399]
[400 … 499]
[500 … 592]
__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]
}
   

關于如何找到當前頁面中出現次數最多的HTML標簽就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI