The href
property sets or gets the entire URL of the current page.
href |
Yes | Yes | Yes | Yes | Yes |
Return the href property.
var v = location.href
Set the href property.
location.href=URL
Value | Type | Description |
---|---|---|
URL | String | Specifies the URL of the link. |
A String type value representing the entire URL.
The following code shows how to get the URL of the current page.
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">test</button>
<p id="demo"></p>
<script>
function myFunction() {<!-- www . ja v a 2 s .c o m-->
var x = location.href;
document.getElementById("demo").innerHTML = x;
}
</script>
</body>
</html>
The code above is rendered as follows:
The following code shows how to set the href value to point to another web site.
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">example.com</button>
<script>
function myFunction() {<!--from w ww . j av a2 s. c o m-->
location.href = "http://www.example.com";
}
</script>
</body>
</html>
The code above is rendered as follows:
The following code shows how to set the href value to point to an anchor within a page.
<!DOCTYPE html>
<html>
<body>
<!-- w w w . j a v a 2 s .c o m-->
<h2><a id="top">There is a link at the bottom of the page!</a></h2>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<button onclick="myFunction()">Go to top</button>
<script>
function myFunction() {
location.href = "#top";
}
</script>
</body>
</html>
The code above is rendered as follows:
The following code shows how to set the href value to point to an email address.
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Send mail</button>
<!-- w ww .ja v a 2s.co m-->
<script>
function myFunction() {
location.href = "mailto:someone@example.com";
}
</script>
</body>
</html>
The code above is rendered as follows: