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.anchors collection returns a live HTMLCollection. This means that if you add or remove anchor elements with name attribute from the DOM, the collection is automatically updated.
  • Only <a> elements with a name attribute 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>
Anchors found: 2
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:

  1. Accesses the document.anchors collection.
  2. Iterates through the collection using a for loop.
  3. Collects the name of each anchor element with name attribute
  4. 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 "anchor1" href changed from "https://example.com/" to "https://codelucky.com/"
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:

  1. Stores the original href attribute.
  2. Modifies the href attribute of all the anchor tags to "https://codelucky.com".
  3. 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>

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;

//]]]]><![CDATA[>
</script>

In this example, we:

  1. Create a few sections with heading tags and give both name and id attributes.
  2. Access the document.anchors collection.
  3. Dynamically create an unordered list (<ul>)
  4. Iterate through each anchor and create a list item (<li>) with an anchor link, that links to specific sections based on the section headings.
  5. Insert this dynamically generated table of contents into the toc div.

Note: This showcases how to create interactive navigation based on the document.anchors collection. πŸ’‘

Browser Compatibility

The document.anchors collection is widely supported by all modern browsers, ensuring compatibility across different platforms.

Note: As the name attribute is deprecated in HTML5 for <a> elements, it is advised to use id attribute instead for creating anchor links and use javascript to query these elements if needed. ⚠️

Conclusion

The document.anchors collection is a useful way to access and manipulate anchor elements within a document using JavaScript, but as it relies on the name attribute which is deprecated, consider using different DOM manipulation techniques. By leveraging this collection, you can dynamically control anchor links, create interactive navigation features, and enhance the overall user experience of your web pages.