萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 取得頁面超連結總數:document.links.length 完整教學

前言

document.links.length 可快速取得文檔中**擁有 href 屬性的 <a> 與 <area> 元素總數**。本文說明用法、統計範圍、動態變化與實務應用。

基本語法

const count = document.links.length; // Number

完整範例

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>連結計數範例</title>
</head>
<body>
  <img src="planets.gif" width="145" height="126" alt="Planets" usemap="#planetmap">
  <map name="planetmap">
    <area shape="rect" coords="0,0,78,125" href="sun.htm" alt="Sun">
    <area shape="circle" coords="88,60,5" href="mercury.htm" alt="Mercury">
    <area shape="circle" coords="125,60,9" href="venus.htm" alt="Venus">
  </map>
  <p><a href="/js/">JavaScript Tutorial</a></p>
  <p>連結/區域總數:<span id="count"></span></p>
  <script>
    document.getElementById('count').textContent = document.links.length;
  </script>
</body>
</html>

輸出:4 (3 個 <area> + 1 個 <a>)

統計範圍詳解

  • 包含:<a href="...">、<area href="..."> (映射圖熱點)。
  • 不包含:無 href 的 <a> (如 <a name="...">、<a id="..." onclick="...">)、<link>、JS 動態跳轉元素。
  • 即時性:HTMLCollection 即時反映 DOM 變化,無需重新查詢。

進階:分類統計

function countLinksByType() {
  let aCount = 0, areaCount = 0;
  for (const link of document.links) {
    if (link.tagName === 'A') aCount++;
    else if (link.tagName === 'AREA') areaCount++;
  }
  return { a: aCount, area: areaCount, total: aCount + areaCount };
}
console.log(countLinksByType()); // {a:1, area:3, total:4}

進階:站內/站外連結計數

function countInternalExternal() {
  let internal = 0, external = 0;
  for (const link of document.links) {
    // 解析 hostname (href 為完整 URL)
    try {
      const url = new URL(link.href);
      url.hostname === location.hostname ? internal++ : external++;
    } catch {
      external++; // 非標準 URL 視為外部
    }
  }
  return { internal, external };
}

動態監控連結數量變化

let lastCount = document.links.length;
const observer = new MutationObserver(() => {
  const current = document.links.length;
  if (current !== lastCount) {
    console.log(`連結數變化: ${lastCount} -> ${current}`);
    lastCount = current;
  }
});
observer.observe(document.body, { childList: true, subtree: true });

常見誤區

誤區正確認知
以為包含所有 <a> 標籤**必須有 href 屬性** 才計入
以為不含 <area>**映射圖熱點區域也計入**
以為是靜態快照**HTMLCollection 即時更新**
用於 SEO 連結計數搜尋引擎爬蟲看 HTML 原始碼,JS 動態產生的連結可能不計

現代替代方案

// 靜態快照,支援完整選擇器語法
const allLinks = document.querySelectorAll('a[href], area[href]');
console.log(allLinks.length); // 數值相同,但為 NodeList (靜態)

// 只統計 
const onlyAnchors = document.querySelectorAll('a[href]').length;

總結

document.links.length 是取得頁面可點擊導航元素總數最簡潔的 API,記住「含 area、即時、需 href」三特性。現代專案統計/操作連結建議改用 querySelectorAll('a[href], area[href]') 獲得靜態 NodeList,配合 forEach、filter 等陣列方法更靈活。

copyright © 萬盛學電腦網 all rights reserved