Computer >> Computer tutorials >  >> Programming >> Javascript

How to get a particular anchor in a document in JavaScript?


Javascript anchor tags follow an array-like structure. When we try to display a particular anchor tag we have to use document.anchors.innerHTML method. This method works the same as array methods which are used to display a particular element.

syntax

element = document.anchors[i].innerHTML;

Example-1

In the following example, the first anchor tag, out of 2 anchor tags, is displayed as shown in the output. 

<html>
<body>
<a name="Tutor">Tutorix</a><br>
<a name="Totorial">Tutorialspoint</a><br>
<p id="anchors"></p>
<script>
   document.getElementById("anchors").innerHTML =
   "The first anchor element is: " + document.anchors[0].innerHTML;
</script>
</body>
</html>

Output

Tutorix

Example-2

In the following example, there are 3 anchor elements in which the third element is displayed using document.innerHTML as shown in the output.

<html>
<body>
   <a name="Tutor">Tutorix</a><br>
   <a name="Totorial">Tutorialspoint</a><br>
   <a name="Totorials">Tutorialspoint private ltd</a><br>
<p id="anchors"></p>
<script>
   document.getElementById("anchors").innerHTML =
   "The third element is:" + document.anchors[2].length;
</script>
</body>
</html>

Output

Tutorix
Tutorialspoint
Tutorialspoint private ltd
The third element is:Tutorialspoint private ltd