Javascript has provided document.links.href to get the href attribute of the required link. This method works the same as a method that displays a particular element in an array. Let's discuss it briefly.
Example-1
In the following example, three links were provided. Using document.links.href the 3rd link is executed in the output. It follows the same as an array. The first link will take the 0th index, the second link will take the 1st index and so on.
<html> <body> <a href="https://www.tutorialspoint.com/javascript/index.htm">Javascript</a><br> <a href="https://www.tutorialspoint.com/java8/index.htm">Java</a><br> <a href="https://www.tutorialspoint.com/spring/index.htm">Spring</a> <p id="links"></p> <script> document.getElementById("links").innerHTML = "The href attribute is: " + document.links[2].href; </script> </body> </html>
Output
Javascript Java Spring The href attribute is: https://www.tutorialspoint.com/spring/index.htm
Example-2
In the following example, two links were provided. Using document.links.href the1st link is executed in the output.
<html> <body> <a href="https://www.tutorialspoint.com/javascript/index.htm">Javascript</a><br> <a href="https://www.tutorialspoint.com/java8/index.htm">Java</a>; <p id="links"></p> <script> document.getElementById("links").innerHTML = "The href attribute is: " + document.links[0].href; </script> </body> </html>
Output
Javascript Java The href attribute is: https://www.tutorialspoint.com/javascript/index.htm