HTML DOM Document links
Example
Number of links in the document:
let numb = document.links.length;
Try it Yourself »
Get the URL of the first link in the document:
let url = document.links[0].href;
Try it Yourself »
Get the URL of the first link in the document:
let url = document.links.item(0).href;
Try it Yourself »
More examples below.
Description
The links
property returns a collection of all links in the document.
The links
property returns an HTMLCollection.
The links
property is read only.
The links in the collection represents <a> and <area> elements with an href attribute.
See Also:
HTMLCollection
An HTMLCollection is an array-like collection (list) of HTML elements.
The length Property returns the number of elements in the collection.
The elements can be accessed by index (starts at 0).
An HTMLCollection is live. It is automatically updated when the document is changed.
Syntax
document.links
Properties
Property | Description |
length | The number of elements in the collection. |
Methods
Method | Description |
[index] | Returns the element with the specified index (starts at 0). Returns null if the index is out of range. |
item(index) | Returns the element with the specified index (starts at 0). Returns null if the index is out of range. |
namedItem(id) | Returns the element with the specified id. Returns null if the id does not exist. |
Return Value
Type | Description |
Object | An HTMLCollection Object. All <a> and <area> elements in the document. The elements are sorted as they appear in the document. |
More Examples
Get the URL of the element with id="myLink":
let url = document.links.namedItem("myLink").href;
Try it Yourself »
Add a red border to the first link in the document:
document.links[0].style.border = "5px solid red";
Try it Yourself »
Loop over all links and output the URL (href) of each:
const links = document.links;
let text = "";
for (let i = 0; i < links.length; i++) {
text += links[i].href + "<br>";
}
Try it Yourself »
Browser Support
document.links
is a DOM Level 1 (1998) feature.
It is fully supported in all browsers:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | 9-11 |