document.anchors is deprecated. Keep it only for understanding or maintaining older pages. New code should use normal elements with id values and DOM selectors.The document.anchors property returns a collection of old-style anchors created with a name attribute. It does not represent the modern pattern of using element IDs for fragment navigation.
const oldNamedAnchors = document.anchors;
console.log(oldNamedAnchors.length);
Older pages sometimes created a navigation target by placing name on an <a> element.
<a name="chapter-2"></a>
The original Plus2net example demonstrated reading length, name, href, and link text from that legacy collection. That behavior is preserved here as historical reference.
for (const anchor of document.anchors) {
console.log(anchor.name, anchor.textContent, anchor.href);
}
The collection's length works like other DOM collections. See array length for the related JavaScript concept, while remembering that an HTMLCollection is not an Array.
Give the destination element an id, then link to that fragment. The destination does not need to be an empty anchor element.
<h2 id="chapter-2">Chapter 2</h2>
<a href="#chapter-2">Go to Chapter 2</a>
const target = document.getElementById("chapter-2");
const fragmentLinks = document.querySelectorAll('a[href^="#"]');
This is clearer and works with semantic headings, sections, form controls, or any other element that can carry an id.
When updating an old page, move the identifier to the actual target element where practical:
<!-- Legacy -->
<a name="pricing"></a>
<h2>Pricing</h2>
<!-- Modern -->
<h2 id="pricing">Pricing</h2>
document Object
URL of the page
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.