The JavaScript Diaries: Part 10

By Lee Underwood

The location Object

This object provides access to and control over the URL of the current window. For security reasons, it cannot modify the URL displayed in the browser's address box.

Properties Methods


You can display each property of the location object by using the script below. (Some of the properties might not display, depending upon the URL that is accessed.)

document.write("hash: "+location.hash+"<br>");
document.write("host: ""<br>");
document.write("hostname: "
  // combine with line above
document.write("URL: "+location.href+"<br>");
document.write("pathname: "
  // combine with line above
document.write("port: "+location.port+"<br>");
document.write("protocol: "
  // combine with line above
document.write("search: ";

Click here to see the results of a revised version of the script above (a new window will open).


The majority of the properties provide information about the document's relation to the server it resides on. They are useful in extracting portions of the URL for use in scripts.


This property is used to navigate to areas on a page designated with the anchor tag, <a name="Note2">...</a>. The links to these type of URLs produce a hash, i.e., <a href="#2">...</a>. (Since it won't look like a link to the browser, you might want to add a style element to it: style="cursor:pointer"). An example of its use would be:

<a onClick=location.hash="Note2"
  style="cursor:pointer">Update on Tech News</a>
   // combine the two lines above


This property returns the name of the host and the port, if included. It combines both the location.hostname and location.port properties. If there is no port number, only the name of the host is given, as in the location.hostname property. If there is a port, the property would return a result something like:; otherwise, it would just be the host name: An example of its use would be:

document.write("host: ";


This property returns the name of the host, i.e. An example of its use would be:

document.write("host: "+location.hostname);


This property contains the entire URL. It's used to load a URL into the browser window. An example of its use would be:


It can also be used to load a new document:


You can also load other types of files directly:


<input type="button" name="Music" value="Play Music"

Page 4 of 5

Previous Page
1 2 3 4 5
Next Page

Make a Comment

Loading Comments...

  • Web Development Newsletter Signup

    Invalid email
    You have successfuly registered to our newsletter.
Thanks for your registration, follow us on our social networks to keep up-to-date