HTML Document anchors Collection: Accessing Anchor Elements
The document.anchors collection in JavaScript provides a way to access all the <a> (anchor) elements within an HTML document. These anchor elements typically create hyperlinks, and this collection allows developers to manipulate these links dynamically using JavaScript. This guide will explore how to use document.anchors to access, iterate through, and modify anchor elements in your web pages.
What is the document.anchors Collection?
The document.anchors collection is a live HTMLCollection that contains all the <a> elements within an HTML document that have a name attribute. It’s essential to note that only anchors with a name attribute are included in this collection, not all anchor tags present in the document.
Purpose of the document.anchors Collection
The primary purposes of using the document.anchors collection are:
- To programmatically access anchor elements and their attributes.
- To dynamically modify anchor links based on user interactions or other conditions.
- To implement advanced navigation features and other interactive functionalities.
- To collect and process all named anchor elements in a document.
Syntax and Usage
The document.anchors property is straightforward to use. It doesn't require any methods to be called; it simply returns the collection of anchor elements with name attribute.
const anchorCollection = document.anchors;
Key Points:
- The
document.anchorscollection returns a liveHTMLCollection. This means that if you add or remove anchor elements withnameattribute from the DOM, the collection is automatically updated. - Only
<a>elements with anameattribute are included. - The elements in the collection are ordered according to their appearance in the HTML source code.
Working with the document.anchors Collection
Let's explore how to use the document.anchors collection with several practical examples.
Basic Example: Accessing Anchors
This basic example demonstrates how to access the document.anchors collection and display information about the anchor elements.
<a name="section1">Section 1</a><br><br>
<a href="#section1">Go to Section 1</a><br><br>
<a name="section2">Section 2</a><br><br>
<a href="#section2">Go to Section 2</a><br><br>
<a href="https://example.com">External Link</a>
<p id="output1"></p>
<script>
//<![CDATA[
const anchorCollection1 = document.anchors;
let outputText1 = "Anchors found: " + anchorCollection1.length + "<br>";
for (let i = 0; i < anchorCollection1.length; i++) {
outputText1 += "Anchor " + (i + 1) + ": Name = " + anchorCollection1[i].name + "<br>";
}
document.getElementById('output1').innerHTML = outputText1;
//]]]]><![CDATA[>
</script>
Anchor 1: Name = section1
Anchor 2: Name = section2
In this example, we first define a few anchor elements, some with a name attribute and others without. The JavaScript code then:
- Accesses the
document.anchorscollection. - Iterates through the collection using a
forloop. - Collects the name of each anchor element with
nameattribute - Displays the number of anchors and the name of each anchor to the output paragraph.
Note: Notice that the external link and anchor tags without the name attribute are ignored. 💡
Modifying Anchor Attributes
This example shows how to modify the href attribute of each anchor element dynamically.
<a name="anchor1" href="https://example.com">Anchor 1</a><br><br>
<a name="anchor2" href="https://example.net">Anchor 2</a><br><br>
<a name="anchor3">Anchor 3</a><br><br>
<p id="output2"></p>
<script>
//<![CDATA[
const anchorCollection2 = document.anchors;
let outputText2 = "";
for(let i = 0; i < anchorCollection2.length; i++){
const anchor = anchorCollection2[i];
const originalHref = anchor.href;
anchor.href = "https://codelucky.com";
outputText2 += `Anchor "${anchor.name}" href changed from "${originalHref}" to "${anchor.href}"<br>`;
}
document.getElementById('output2').innerHTML = outputText2;
//]]]]><![CDATA[>
</script>
Anchor "anchor2" href changed from "https://example.net/" to "https://codelucky.com/"
Anchor "anchor3" href changed from "" to "https://codelucky.com/"
Here, the JavaScript code iterates through each named anchor and:
- Stores the original
hrefattribute. - Modifies the
hrefattribute of all the anchor tags to"https://codelucky.com". - Outputs a message indicating the change of each anchor's
href.
Note: This is a basic example of how you can manipulate anchor links dynamically. 📝
Using forEach to Iterate
The forEach method is another way to iterate over the HTMLCollection. This example demonstrates how to use forEach to collect and display anchor data.
<a name="link1" href="#top">Link 1</a><br><br>
<a name="link2" href="https://example.org">Link 2</a><br><br>
<a name="link3">Link 3</a>
<p id="output3"></p>
<script>
//<![CDATA[
const anchorCollection3 = document.anchors;
let outputText3 = "";
anchorCollection3.forEach(function(anchor, index) {
outputText3 += "Anchor " + (index+1) + ": Name = " + anchor.name + ", href = " + anchor.href + "<br>";
});
document.getElementById('output3').innerHTML = outputText3;
//]]]]><![CDATA[>
</script>
Anchor 2: Name = link2, href = https://example.org/
Anchor 3: Name = link3, href = http://127.0.0.1:5500/html-document-anchors-collection.html#
This example uses the forEach method for iterating over the document.anchors collection, making the code cleaner and more readable. It retrieves and displays the name and href attributes of each anchor.
Note: forEach is a concise way to loop through collections. ✅
Real-World Example: Table of Contents
Here is a more practical example of how you might use the document.anchors collection to create a simple table of contents dynamically.
<h2 id="sectionA" name="sectionA">Section A</h2>
<p>Content for Section A...</p>
<h2 id="sectionB" name="sectionB">Section B</h2>
<p>Content for Section B...</p>
<h2 id="sectionC" name="sectionC">Section C</h2>
<p>Content for Section C...</p>
<div id="toc"></div>
<script>
//<![CDATA[
const anchorsCollection4 = document.anchors;
const tocContainer4 = document.getElementById('toc');
let tocHTML4 = "<ul>";
anchorsCollection4.forEach(anchor => {
tocHTML4 += `<li><a href="#${anchor.name}">${anchor.name}</a></li>`;
});
tocHTML4 += "</ul>";
tocContainer4.innerHTML = tocHTML4;
//]]]]><







