JavaScript Location Object

« Previous Tutorial Next Tutorial »

The location object in JavaScript helps in storing the information of current URL of the window object. It is a child object of the window object.

The location object has the following two features:

JavaScript Location Object Properties

The table given below describes the properties of the Location object in JavaScript.

Property Description Example
href represents a string specifying the entire URL
protocol represents a string at the beginning of a URL up to the first colon (:), which specifies the method of access to the URL http: or https:
host represents a string consisting of the hostname and port strings
hostname represents the server name, subdomain, and domain name of a URL
port represents a string specifying the communications port that the server uses 80
pathname represents a string portion of a URL specifying how a particular resource can be accessed test.asp
search represents a string beginning with a question mark that specifies any query information in an HTTP URL id=1
hash represents a string beginning with a # specifies an anchor name in an HTTP URL start

JavaScript Location Object Methods

The following table lists the methods of the Location object in JavaScript.

Method Description
assign() Loads a new document in the browser
reload() reloads the current document that is contained in the location.href property
replace() replaces the current document with the specified new one, you can not navigate back to the previous document using the browser's Back button

JavaScript Location Object Example

Here is an example demonstrates location object in JavaScript:

	<title>JavaScript Location Object</title>
	<script type="text/javascript">
		function gotoUrl()
			window.location.href = window.document.loctn.ProtocolFld.
			text + document.loctn.HostnameFld.value + document.loctn.

<h3>Enter URL in following sections</h3>
<form name="loctn" method="post">
<select name="ProtocolFld" size="1">
<input type="text" size="20" maxlength="256" name="HostnameFld" value="">
<input type="text" size="20" maxlength="100" name="PathnameFld" value="/">
<input type="button" name="Go" value="Go" onclick="gotoUrl()">

Here is the sample output of the above JavaScript location object example code:

javascript location object

Now fill (or edit and fill) the required field as shown in the following snapshot:

location object

After filling the required field as shown in the above figure, click on Go button to go to that url. Here is the sample output after clicking on the Go button:

javascript location example

« Previous Tutorial Next Tutorial »

Latest 5 Posts by CodesCracker


Quick Links
Signup - Login - Give Online Test