Javascript has provided document.href and document.target to get the href and target attributes in a link. A link is usually placed in a <p> tag and inside it, an anchor tag is provided, which in turn contains href and target attributes. Let's discuss them individually.
Finding href attribute
To get the href attribute, document.href must be used. In the following example, the href attribute consists of a link called "https://www.tutorialspoint.com/", which will be displayed once the program is executed.
Example
<html> <body> <p><a id="myId" href="https://www.tutorialspoint.com/">tutorialspoint</a></p> <script> var ref = document.getElementById("myId").href; document.write(ref); </script> </body> </html>
Output
tutorialspoint https://www.tutorialspoint.com/
Finding the target attribute
To get the target attribute, document.target must be used. In the following example, the target attribute "_union" was displayed when the program was executed.
Example
<html> <body> <p><a id="myId" target="_union" href="https://www.tutorialspoint.com/">tutorialspoint</a></p> <script> var ref = document.getElementById("myId").target; document.write(ref); </script> </body> </html>
Output
tutorialspoint _union