萬盛學電腦網

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

JavaScript 取得頁面第一個連結 ID:document.links[0].id 完整教學

前言

document.links 回傳文檔中所有擁有 href 屬性的 <a> 與 <area> 元素組成的 **HTMLCollection** (即時集合)。本文示範如何取得第一個連結的 id 屬性,並延伸相關操作。

基本語法

const firstLinkId = document.links[0]?.id; // 可選鏈防報錯

完整範例

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>第一個連結 ID</title>
</head>
<body>
  <h1>sharejs.com</h1>
  <img src="planets.gif" width="145" height="126" alt="Planets" usemap="#planetmap">
  <map name="planetmap">
    <area id="sun" shape="rect" coords="0,0,82,126" href="sun.htm" alt="Sun">
    <area id="mercury" shape="circle" coords="90,58,3" href="mercur.htm" alt="Mercury">
    <area id="venus" shape="circle" coords="124,58,8" href="venus.htm" alt="Venus">
  </map>
  <p><a id="javascript" href="/js/">JavaScript Tutorial</a></p>
  <p>第一個連結/區域 ID:<span id="output"></span></p>
  <script>
    const firstLink = document.links[0];
    document.getElementById('output').textContent = firstLink ? firstLink.id : '無連結';
  </script>
</body>
</html>

輸出:sun (因 <area> 在 DOM 順序上先於 <a>)。

document.links 詳細特性

特性說明
元素類型<a href>、<area href> (映射圖熱點)
集合類型HTMLCollection (即時、類陣列、不可疊代器)
順序文檔順序 (DFS 深度優先)
長度document.links.length
索引存取document.links[i]
名稱存取document.links['name'] (對應 name 或 id)

進階操作範例

1. 取得所有連結 URL 陣列

const urls = Array.from(document.links).map(a => a.href);
console.log(urls);

2. 過濾站外連結並加上 target="_blank"

Array.from(document.links).forEach(a => {
  if (a.hostname !== location.hostname) {
    a.target = '_blank';
    a.rel = 'noopener noreferrer';
  }
});

3. 監聽動態新增連結 (MutationObserver)

const observer = new MutationObserver(() => {
  const newLinks = [...document.links].filter(l => !l.dataset.processed);
  newLinks.forEach(l => { l.dataset.processed = '1'; /* 初始化 */ });
});
observer.observe(document.body, { childList: true, subtree: true });

document.links vs document.anchors vs document.querySelectorAll

集合包含元素即時性典型用途
document.links<a href>, <area href>即時導航、外連處理、站點地圖
document.anchors<a name> (錨點,**已棄用**,HTML5 改用 id)即時舊式頁內跳轉
document.querySelectorAll('a[href]')<a href> (不含 area)靜態快照現代選擇器、需篩選屬性

注意事項

  • <a> **無 href 不計入** document.links (如 <a name="anchor"> 或純 JS 觸發器)。
  • id 可能為空字串,link.id 回傳 "",非 null。
  • HTMLCollection **即時更新**,迴圈中修改 DOM 可能導致索引錯位,建議 Array.from() 轉陣列再處理。
  • 跨域 iframe 內的連結**不包含**在父頁面 document.links 中。

總結

document.links[0].id 即可取得文檔順序第一個超連結/熱點區域的 ID。現代開發推薦 document.querySelector('a[href], area[href]') 語意更明確、回傳單一元素、支援複雜選擇器。理解 HTMLCollection 即時特性與 <area> 也屬於 links 集合,能避免「以為第一個是 <a> 實際是 <area>」的誤區。

copyright © 萬盛學電腦網 all rights reserved