The href
property sets or gets the value of the href
attribute of a link.
We can set an absolute URL, for example href="http://www.example.com/default.htm"
.
Or we can use a relative URL, for example href="index.htm"
.
We can also use an anchor URL which points to an anchor within a page, like href="#top"
.
When used in getter, it returns the URL of the link.
It returns the entire URL, including the protocol, for example http://
.
Change the URL of a link:
document.getElementById("myAnchor").href = "http://www.example.com/";
Click the button to change the value of the href
attribute of the link.
<!DOCTYPE html> <html> <body> <p><a id="myAnchor" href="http://www.example.com">examples</a></p> <button onclick="myFunction()">Test</button> <p id="demo"></p> <script> function myFunction() {//from w ww. ja va 2 s . c om document.getElementById("myAnchor").href = "http://www.java2s.com/"; document.getElementById("demo").innerHTML = "The link url changed."; } </script> </body> </html>