JavaScript: Page Location

Whether you're a seasoned developer or just starting your journey, understanding how to manipulate the web page's location through JavaScript can be a very useful tool in your arsenal.

From redirecting users to different pages to extracting valuable information about the current URL, location offers a wealth of functionality that every developer should master.

The Location Object

The location object can be accessed using the following ways:

  • location
  • window.location
  • document.location

Here's a breakdown of the multiple properties that it's comprised of. To understand better, let's take the following example URL:

https://tinyfrontend.com/like/comment?q=follow&page=1#subscribe

Location.href

The whole URL is contained in this property as a string. You can assign a new value to this property to replace the current page with the new one.

// Another webpage on the same website
location.href = "/some/other/path"

// Another website
location.href = 'https://google.com'

// Also Works!!
location = 'https://google.com'

Subscribe to read the full content