Ways to Use window.location.href in JavaScript (4 Demos)

JavaScript window.location.href property

The href is a property of the window.location object that is used to get the complete URL of the existing web page. You can also use window.location.href to set the URL of the current page.

You may simply use the location.href as well instead window.location.href.

Following are few examples of using location.href but let us first look at its syntax:

Syntax to use window.location.href

You can use window.location.href to get URL as follows:

var currURL = window.location.href;

Or simply use:

var currURL = location.href;

In order to set URL for the current page:

window.location.href = “URL”;

Or simply use

location.href = “URL”;

Where URL can be absolute or relative to another file or even existing page’s anchor text.

Now let us look at a few examples of using the JavaScript window.location.href.

JavaScript location.href example to get current URL

Following is an example to get the current URL by using location.href. Click on button “Get URL by location.href JavaScript” and the alert will show you the current URL.

javascript location.href

Experience this example online



Javascript window.location.href example to get current URL

As mentioned earlier, you can use window.location.href as well to get the current path as shown in the example below.

Experience this example online



You can see in above examples result is same for both ways.

document.location.href to get current URL

You can also use document.location.href to get or set URL. Following example shows using the document.location.href to get current URL.

Experience this example online



window.location.href example to set URL

Following example sets the current URL by using window.location.href property. As you click on the button, the current path will be set to goole.com and page will be redirected to given URL.

Experience this example online



In the demo, as you click on button “Set URL by JavaScript window.location.href” the page will be redirected to given URL.

You can also use the relative path to set the current URL within the current domain to another file even anchor text of existing page like “#middle”.

Also see: Javascript innerHTML property


Was this article helpful?

Related Articles

Leave A Comment?