Javascript Location Host with Example

Updated on 22 Mar 2012,
Published on 10 Jul 2008

Javascript location host property sets or returns the host address as domain name or IP of the host. Normally location host property returns the domain name or sub domain name while working online. Javascript location host property returns the combination of port as well as domain name of the web site. It displays the port number only if the port is specified with domain name:

e.g.: www.domainname.com:8080

You can say that Javascript location host property is the combination of location.hostname and location.port properties.

JavaScript Window Location Object Examples:

You can see the live samples and examples of JavaScript Window Location Object from the following links:

When location.host property is used on the local system while developing the web pages, it returns the localhost or IP address of the local system. If your web site is being hosted on the dedicated server having exclusive dedicated IP then you can browse your web site through IP address also. Javascript location host property returns IP address of the domain while browsing the web page using IP of the domain hosting. 

Syntax for Javascript Location Host

location.host

or

window.location.host

You can use any of the above syntax to retrieve the host name.

Following syntax shows how to set the location host property:

location.host = "otherdomainname.com";

Example of Javascript Location Host

<script type="text/javascript" language="javascript">
    function locationHost() {
        alert(window.location.host);
    }
</script>

Above example shows how to retrieve the value of window.location.host property onclick event of button control. You can also call the location.host property openly in javascript using alert message box without placing it inside the javascript function. Openly coded location.host 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 host.

Output:

You can see the output of above discussed code from the following link:

JavaScript window.location.host

Continue to next tutorial: Javascript Location Hostname with Example to learn how to get only domain name from the current URL.

0 Responses to "Javascript Location Host with Example"
Leave a Comment
* required
* required
* will not be published
* optional
* hint: http://www.example.com
  • Subscribe via Email
  • HIRE EzineASP.Net Developers