How to find the href and target attributes in a link in JavaScript?

JavascriptObject Oriented ProgrammingFront End Technology

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 "http://www.tutorialspoint.com/", which will be displayed once the program is executed.

Example

Live Demo

<html>
<body>
<p><a id="myId" href="http://www.tutorialspoint.com/">tutorialspoint</a></p>
<script>
   var ref = document.getElementById("myId").href;
   document.write(ref);
</script>
</body>
</html>

Output

tutorialspoint

http://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

Live Demo

<html>
<body>
<p><a id="myId" target="_union" href="http://www.tutorialspoint.com/">tutorialspoint</a></p>
<script>
   var ref = document.getElementById("myId").target;
   document.write(ref);
</script>
</body>
</html>

Output

tutorialspoint

_union
raja
Published on 25-Jul-2019 17:04:58
Advertisements