HTML DOM
HTML DOM anchors Collection
The anchors collection returns an HTMLCollection of all <a> elements in the document that have a name attribute. It is a live, read-only collection.
Definition and Usage
document.anchors returns an HTMLCollection of every anchor (<a>) element that has a name attribute set. Anchors defined only with an href but no name are not included. Because the collection is live, it updates automatically when anchors are added or removed.
Syntax
document.anchorsAccess individual anchors with document.anchors[index] and count them with document.anchors.length.
Example
<a name="chapter1">Chapter 1</a>
<a name="chapter2">Chapter 2</a>
<a href="#chapter1">Skip (no name, not counted)</a>
<p id="out"></p>
<script>
const anchors = document.anchors;
let text = "Named anchors: " + anchors.length + "<br>";
for (let i = 0; i < anchors.length; i++) {
text += anchors[i].name + "<br>";
}
document.getElementById("out").innerHTML = text;
</script>The result shows a length of 2 and lists chapter1 and chapter2. The third <a> is ignored because it has no name attribute.
The name attribute on <a> is obsolete in HTML5. Modern pages use id for in-page targets, so document.anchors is mostly relevant for legacy documents.
