HTML DOM Anchor Collection

HTMLWeb DevelopmentFront End Technology

The HTML DOM Anchor collection is used to return the collection of all the anchor tags(<a>) present in our HTML document. It will count the links only if they have name attribute associated with them. The name attribute is however deprecated in the current HTML5. The elements appear in the same order as they are present in the html source document.


Following are the properties of Anchor collection.

It will return the number of links(<a>) in our html document.


Following are the methods of Anchor collection.

It will return the link at the specified index. The index starts from 0 and from top to bottom order. Null will be returned if no item found.
It will return the link at the specified index. The index starts from 0. Null will be returned if no item found.
It will return the link from collection with the id specified.Null will be returned if no item found.


Following is the syntax −

For getting anchor collection.


Note − Anchor collection can’t be set as they are read-only .


Let us see an example for anchor collection −

 Live Demo

<!DOCTYPE html>
<a name="example">Sample1</a><br>
<a name="example1">Sample2</a><br>
<a name="example2">Sample3</a><br>
<p>Click the button to get first link text in the above list</p>
<button onclick="getCollection()">Collection</button>
<button onclick="getLength()">Length</button>
<p id="sample"></p>
   function getCollection() {
      var x = document.anchors[0].innerHTML;
      document.getElementById("sample").innerHTML = x;
   function getLength() {
      var x = document.anchors[0].innerHTML.length;
      document.getElementById("sample").innerHTML = x;


It will produce the following output −

On clicking “Collection” button −

On clicking “Length” button −

In the above example −

We have three links with name attribute equals example, example1 and example2 respectively

<a name="example">Sample1</a><br>
<a name="example1">Sample2</a><br>
<a name="example2">Sample3</a> <br>

We then have two buttons collection and length to execute getCollection() and getLength() functions respectively.

<button onclick="getCollection()">Collection</button>
<button onclick="getLength()">Length</button>

The getCollection() function returns the anchor tag text at the 0 index position which in our case is Sample1. The getLength() function returns the length of the link text. Here the link text is Sample1 so the length returned is 7.

Published on 06-Aug-2019 12:40:02