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

How to find the number of links in a document in JavaScript?


Javascript DOM has provided many properties to get the details regarding a document. It has provided a method called document.links.length to get the number of links that a document contains. This method won't disturb the code's normal functionality.

Example-1

In the following example, there are three links provided in the code. Using the DOM property document.links.length the number of links were displayed in the output as shown.

<html>
<body>
   <a href="https://www.tutorialspoint.com/javascript/index.htm">Javascript</a><br>
   <a href="https://www.tutorialspoint.com/php/index.htm">Php</a><br>
   <a href="https://www.tutorialspoint.com/java8/index.htm">Php</a><br>
<p id="links"></p>
<script>
   document.getElementById("links").innerHTML =
   "The number of links are: " + document.links.length;
</script>
</body>
</html>

Output

Javascript
Php
Java
The number of links are: 3


Example-2

In the following example, there are two links provided in the code. Using the DOM property document.links.length the number of links were displayed in the output as shown.

<html>
<body>
   <a href="https://www.tutorialspoint.com/javascript/index.htm">Javascript</a><br>
   <a href="https://www.tutorialspoint.com/bitcoin/index.htm">Bitcoin</a></br>
<script>
   document.write("The number of links are: " + document.links.length);
</script>
</body>
</html>

Output

Javascript
Bitcoin
The number of links are: 2