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);
const count = document.links.length;
console.log(`Links on this page: ${count}`);
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);
}
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 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"]');
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
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.