Javascript Reference - HTML DOM Anchor hostname Property








The hostname property sets or gets the hostname part of the href attribute.

Browser Support

hostname Yes Yes Yes Yes Yes

Syntax

Return the hostname property:

var v = anchorObject.hostname 

Set the hostname property:

anchorObject.hostname = hostname;

Property Values

Value Description
hostname Set the URL hostname




Return Value

A String representing the domain name or IP address.

Example

The following code shows how to get the hostname.


<!DOCTYPE html>
<html>
<body>
<!--from   w w w. j ava 2  s  .c om-->
<p><a id="myAnchor" href="http://www.example.com:80/index.htm#part1">Example link</a></p>
<button onclick="myFunction()">test</button>

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

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

</body>
</html>

The code above is rendered as follows:





Example 2

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


<!DOCTYPE html>
<html>
<body>
<!--from w w w.  ja va  2s .c o  m-->
<p><a id="myAnchor" target="_blank" href="http://www.example.com:1234/index.htm#part1">Example link</a></p>
<button onclick="myFunction()">test</button>

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

<script>
function myFunction() {
    document.getElementById("myAnchor").host = "www.yourfakeserver.com";
    document.getElementById("demo").innerHTML = "changed";
}
</script>

</body>
</html>

The code above is rendered as follows: