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.
Properties
Following are the properties of Anchor collection.
Property | Description |
---|---|
length | It will return the number of links(<a>) in our html document. |
Methods
Following are the methods of Anchor collection.
Method | Description |
---|---|
[Index] | 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. |
item(index) | It will return the link at the specified index. The index starts from 0. Null will be returned if no item found. |
namedItem(id): | It will return the link from collection with the id specified.Null will be returned if no item found. |
Syntax
Following is the syntax −
For getting anchor collection.
document.anchors
Note − Anchor collection can’t be set as they are read-only .
Example
Let us see an example for anchor collection −
<!DOCTYPE html> <html> <body> <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> <script> 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; } </script> </body> </html>
Output
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.