How to find the href attribute of a link in a document in JavaScript?

JavascriptObject Oriented ProgrammingFront End Technology

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. 

Live Demo

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

Live Demo

<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
raja
Published on 26-Jul-2019 15:38:24
Advertisements