JavaScript document.links: Access Links in a Page

The read-only document.links property returns an HTMLCollection containing the document's <a> and <area> elements that have an href value.

const linkCount = document.links.length;
console.log(linkCount);
Table of Contents

Count Links in the Document Top ↑

const count = document.links.length;
console.log(`Links on this page: ${count}`);

Read the First Link Top ↑

Collections use zero-based indexes. Check the length before reading an item.

if (document.links.length > 0) {
  const firstLink = document.links[0];
  console.log(firstLink.href);
  console.log(firstLink.textContent);
}

Loop Through All Links Top ↑

The original tutorial used an index-based for loop and document.write(). A modern for...of loop is simpler for reading the collection:

for (const link of document.links) {
  console.log(link.href);
}

To create visible output, append elements or text instead of writing into the document stream:

const list = document.getElementById("linkList");

for (const link of document.links) {
  const item = document.createElement("li");
  item.textContent = link.href;
  list.append(item);
}

document.links vs querySelectorAll() Top ↑

document.links is convenient when you specifically want link-capable elements with href. CSS selectors are more flexible when the page needs a subset.

const navLinks = document.querySelectorAll("nav a[href]");
const externalLinks = document.querySelectorAll('a[href^="http"]');

HTMLCollection Behavior Top ↑

document.links is a live collection. If matching links are added or removed from the DOM, its contents can update automatically. If you need a fixed snapshot for later processing, copy it into an array.

const snapshot = Array.from(document.links);
document Object URL of the page


Subscribe to our YouTube Channel here



plus2net.com










✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer