Javascript Reference - HTML DOM Anchor href Property








The href property sets or gets the value of the href attribute of a link.

Browser Support

href Yes Yes Yes Yes Yes

Syntax

Return the href property:

var v = anchorObject.href 

Set the href property:

anchorObject.href = URL;

Property Values

Value Description
URL Specifies the URL of the link.
Possible values:
  • An absolute URL - href='http://www.example.com'
  • A relative URL - href='default.htm'
  • An anchor URL - href='#top'




Return Value

A String representing the URL of the link.

Example

The following code shows how to change the URL of a link.


<!DOCTYPE html>
<html>
<body>
<!--from  www .j a v a 2 s  . c  om-->
<p><a id="myAnchor" href="http://www.example.com">www.example.com</a></p>
<button onclick="myFunction()">test</button>

<p id="demo"></p>

<script>
function myFunction() {
    document.getElementById("myAnchor").href = "http://www.google.com/";
    document.getElementById("demo").innerHTML = "changed";
}
</script>

</body>
</html>

The code above is rendered as follows:





Example 2

The following code shows how to get the URL of a link.


<!DOCTYPE html>
<html>
<body>
<!--from w  w  w .ja  va  2 s .co  m-->
<p><a id="myAnchor" href="http://www.example.com">example</a></p>
<button onclick="myFunction()">test</button>

<p id="demo"></p>

<script>
function myFunction() {
    var x = document.getElementById("myAnchor").href;
    document.getElementById("demo").innerHTML = x;
}
</script>

</body>
</html>

The code above is rendered as follows: