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

How to find a number of anchors in a document in JavaScript?


Anchor tags are very common when dealing with a document in javascript. Javascript has provided document.anchors .length to get the number of anchors in a document. This method won't affect any other line codes in the program. It only renders the length of the anchor tags.

syntax

length = document.anchors.length;

It returns only the number of anchor tags without affecting any other lines of code.

Example-1

In the following example, two anchor tags were used and their length was displayed using DOM property document.anchors.length 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 number of anchors are: " + document.anchors.length;
</script>
</body>
</html>

Output

Tutorix
Tutorialspoint
The number of anchors are: 2

Example-2

In the following example, three anchor tags were used and their length was displayed using document.anchors.length 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>
<script>
   document.write(document.anchors.length);
</script>
</body>
</html>

Output

Tutorix
Tutorialspoint
Tutorialspoint private ltd
3