HTML DOM Document links attribute

Definition and Usage

links The attribute returns a collection of all links in the document.

links The property returns HTMLCollection.

links The property is read-only.

The links in the collection represent the <a> and <area> elements that have the href attribute.

See also:

HTML DOM Anchor Object

HTML DOM Area Object

HTML <a> Tag

HTML <area> Tag

HTML Links

HTMLCollection

HTMLCollection It is a similar array collection (list) of HTML elements.

You can access the elements in the collection by index (starting from 0).

length The property returns the number of elements in the collection.

Instance

Example 1

Return the number of links in the document:

let numb = document.links.length;

Try it yourself

Example 2

Get the URL of the first link in the document:

let url = document.links[0].href;

Try it yourself

Example 3

Get the URL of the first link in the document:

let url = document.links.item(0).href;

Try it yourself

Example 4

Get the URL of the element with id="myLink":

let url = document.links.namedItem("myLink").href;

Try it yourself

Example 5

Add a red border to the first link in the document:

document.links[0].style.border = "5px solid red";

Try it yourself

Example 6

Traverse all links and output the URL (href) of each link:

const links = document.links;
let text = "";
for (let i = 0; i < links.length; i++) {
  text += links[i].href + "<br>";
}

Try it yourself

Syntax

document.links

Property

Property Description
length The number of elements in the collection.

Method

Method Description
[index]

Returns the element with the specified index (starting from 0).

If the index is out of range, returns null.

item(index)

Returns the element with the specified index (starting from 0).

If the index is out of range, returns null.

namedItem(id)

Returns the element with the specified id element.

If id If it does not exist, returns null.

Return value

Type Description
Object

HTMLCollection object.

All <a> and <area> elements in the document.

Sorted in the order they appear in the source code.

Browser support

document.links It is a DOM Level 1 (1998) feature.

It is supported by all browsers:

Chrome IE Edge Firefox Safari Opera
Chrome IE Edge Firefox Safari Opera
Support 9-11 Support Support Support Support