HTML Document links Collection: Accessing Link Elements

The document.links collection in JavaScript provides a convenient way to access all the <a> (anchor) elements within an HTML document. This collection returns an HTMLCollection, which is an array-like object containing all the link elements present in the document. This article will explore how to use the document.links collection, demonstrating various practical examples.

Understanding the document.links Collection

The document.links collection is a read-only property of the document object. It returns an HTMLCollection of all the <a> elements that have an href attribute. This is particularly useful for programmatically inspecting or modifying the links on a page.

Key Features:

  • Read-only: You cannot directly modify the collection; you can only access its elements.
  • Live Collection: The HTMLCollection is live, meaning it automatically updates if new links are added to or removed from the document.
  • Array-like: Although not a true array, you can access elements using index notation ([0], [1], etc.) and iterate over it using loops.

Syntax

The syntax to access the document.links collection is straightforward:

const linksCollection = document.links;

Practical Examples

Let’s explore various practical examples demonstrating how to use the document.links collection.

Basic Access and Iteration

This example demonstrates accessing the links collection and iterating through its elements to list all the links on the page.

<!DOCTYPE html>
<html>
<head>
    <title>Document Links Example</title>
</head>
<body>
    <a href="https://codelucky.com">CodeLucky</a>
    <a href="https://example.com">Example</a>
    <a href="https://w3schools.com">W3Schools</a>

    <ul id="linkList"></ul>

<script>


      const links_ex1 = document.links;
      const linkList_ex1 = document.getElementById('linkList');

      for (let i = 0; i < links_ex1.length; i++) {
        const linkItem = document.createElement('li');
        linkItem.textContent = links_ex1[i].href;
        linkList_ex1.appendChild(linkItem);
      }


</script>

</body>
</html>

Output:

  • https://codelucky.com
  • https://example.com
  • https://w3schools.com

This script iterates over each link in the document.links collection and creates a list item with the href of each link.

This example shows how to get the total number of links present in the document.

<!DOCTYPE html>
<html>
<head>
    <title>Number of Links Example</title>
</head>
<body>
    <a href="https://codelucky.com">CodeLucky</a>
    <a href="https://example.com">Example</a>

    <p id="linkCount_ex2"></p>

<script>


      const links_ex2 = document.links;
      const linkCount_ex2 = document.getElementById('linkCount_ex2');
      linkCount_ex2.textContent = "Number of links: " + links_ex2.length;


</script>

</body>
</html>

Output:

Number of links: 2

The script retrieves the length property of the links collection to display the total number of links in the document.

Modifying Link Attributes

This example shows how to modify the attributes of link elements using the links collection.

<!DOCTYPE html>
<html>
<head>
    <title>Modify Link Attributes Example</title>
</head>
<body>
    <a href="https://codelucky.com">CodeLucky</a>
    <a href="https://example.com">Example</a>

<script>


      const links_ex3 = document.links;
      for (let i = 0; i < links_ex3.length; i++) {
        links_ex3[i].target = "_blank";
        links_ex3[i].style.color = 'blue';
      }


</script>

</body>
</html>

This script iterates over each link and sets the target attribute to "_blank" (which opens the link in a new tab/window) and also changes the text color to blue.

Filtering Links Based on URL

This example demonstrates how to filter links based on their URL and perform specific actions.

<!DOCTYPE html>
<html>
<head>
    <title>Filter Links Example</title>
</head>
<body>
    <a href="https://codelucky.com">CodeLucky</a>
    <a href="https://example.com">Example</a>
     <a href="https://codelucky.com/blog">CodeLucky Blog</a>
     <p id="filteredLinks_ex4"></p>

<script>


      const links_ex4 = document.links;
      const filteredLinks_ex4 = document.getElementById('filteredLinks_ex4');
      let codeluckyLinks = [];
      for (let i = 0; i < links_ex4.length; i++) {
        if (links_ex4[i].href.includes('codelucky.com')) {
          codeluckyLinks.push(links_ex4[i].href);
        }
      }
      filteredLinks_ex4.textContent = "Links to CodeLucky: " + codeluckyLinks.join(', ');


</script>

</body>
</html>

Output:

Links to CodeLucky: https://codelucky.com, https://codelucky.com/blog

This script filters all links and collect the ones including the string “codelucky.com” in their href attribute. It then displays the collected links separated by a comma.

Working with Live Collection

This example illustrates the live nature of the links collection by dynamically adding a new link to the document and observing the collection update in real-time.

<!DOCTYPE html>
<html>
<head>
    <title>Live Collection Example</title>
</head>
<body>
    <a href="https://codelucky.com">CodeLucky</a>
     <p id="linkCountLive_ex5"></p>
    <button id="addLinkBtn_ex5">Add Link</button>

<script>


      const links_ex5 = document.links;
      const linkCountLive_ex5 = document.getElementById('linkCountLive_ex5');
      const addLinkBtn_ex5 = document.getElementById('addLinkBtn_ex5');

      function updateLinkCount() {
        linkCountLive_ex5.textContent = "Number of links: " + links_ex5.length;
      }

      addLinkBtn_ex5.addEventListener('click', () => {
        const newLink = document.createElement('a');
        newLink.href = "https://newlink.com";
        newLink.textContent = "New Link";
        document.body.appendChild(newLink);
        updateLinkCount();
      });
      updateLinkCount();


</script>

</body>
</html>

Output:
Initially the number of links will be 1, after clicking the “Add Link” button, a new link will be added to the page and the number of links count will be updated to 2.

This example displays the number of links on the page. When the “Add Link” button is clicked, a new link is added to the body, and the displayed link count updates automatically, showcasing the live behavior of the document.links collection.

Important Considerations

  • href Attribute: The document.links collection only includes <a> elements with an href attribute. Links without an href will not be included.
  • Read-Only: While you can’t modify the collection directly (e.g., adding or removing elements from it), you can modify the elements within the collection.
  • Performance: When dealing with large documents containing many links, be cautious when performing complex operations on all links, as it may impact performance.

Browser Support

The document.links collection is supported in all modern browsers, making it a reliable tool for web development.

Browser Support
Chrome
Firefox
Safari
Edge
Opera

Conclusion

The document.links collection is an essential tool for accessing and manipulating link elements in HTML documents. By understanding how to use this collection, developers can easily perform tasks like listing links, modifying link attributes, and filtering links based on their URLs. The live nature of the collection also makes it useful for building dynamic web applications where links are frequently added or changed. This provides a powerful capability for managing and interacting with links programmatically.