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

JavascriptObject Oriented ProgrammingFront End Technology

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.

Live Demo

<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.

Live Demo

<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
raja
Published on 26-Jul-2019 14:54:16
Advertisements