文件:anchors 屬性

已棄用:此特性不再推薦。雖然某些瀏覽器可能仍然支援它,但它可能已經從相關的網路標準中刪除,可能正在刪除過程中,或者可能僅為相容性目的而保留。請避免使用它,如果可能,請更新現有程式碼;請參閱本頁底部的相容性表格以指導您的決策。請注意,此特性可能隨時停止工作。

Document 介面的只讀屬性 anchors 返回文件中所有錨點的列表。

一個 HTMLCollection

示例

基本用法

js
if (document.anchors.length >= 5) {
  console.log("found too many anchors");
}

建立目錄

以下示例將自動填充頁面上每個錨點的目錄:

html
<h1>Title</h1>
<h2><a name="contents">Contents</a></h2>
<ul id="toc"></ul>

<h2><a name="plants">Plants</a></h2>
<ol>
  <li>Apples</li>
  <li>Oranges</li>
  <li>Pears</li>
</ol>

<h2><a name="veggies">Veggies</a></h2>
<ol>
  <li>Carrots</li>
  <li>Celery</li>
  <li>Beats</li>
</ol>
js
const toc = document.getElementById("toc");
for (const anchor of document.anchors) {
  const li = document.createElement("li");
  const newAnchor = document.createElement("a");
  newAnchor.href = `#${anchor.name}`;
  newAnchor.textContent = anchor.text;
  li.appendChild(newAnchor);
  toc.appendChild(li);
}

注意

出於向後相容的原因,返回的錨點集合僅包含使用 name 屬性建立的錨點,而不包含使用 id 屬性建立的錨點。

規範

規範
HTML
# dom-document-anchors

瀏覽器相容性