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 等陣列方法更靈活。