Javascript location hostname property sets or returns the hostname i.e domain name or IP address of the host. There is a difference between location.hostname and location.host that location host property returns both host name and port number where as location hostname property returns only host name i.e. the domain name of the current web site. If you are accessing a web site using its IP address then Javascript location hostname also returns the IP address displayed in the address bar of the web browser. While developing a web site on localhost, location.hostname returns localhost or local IP address of the system.
Syntax for Javascript Location Hostname Property
location.hostname
or
window.location.hostname
Both above syntax will return the same hostname value.
Following syntax can be used to set the location hostname property value:
location.hostname = "otherdomain.com";
Example of Javascript Location Hostname Property
<script type="text/javascript" language="javascript">
function locationHostname() {
alert(window.location.hostname);
}
</script>
Above example shows how to retrieve the value of window.location.hostname property onclick event of button control. You can also call the location.hostname property openly in javascript using alert message box without placing it inside the javascript function. Openly coded location.hostname property in a Javascript code block placed inside the HTML <head> section will call the script at body or page load and will show the hostname directly.
Continue to next tutorial: Javascript Location Port with Example to learn how to get the port number using JavaScript.