Skip to content
Related Articles
Open in App
Not now

Related Articles

How to set location and location.href using JavaScript ?

Improve Article
Save Article
  • Last Updated : 13 Jan, 2023
Improve Article
Save Article

In this article, we will set the location and location.href using Javascript.

Both location and location.href are used to set or return the complete URL of your current page. They return a string that contains the entire URL with the protocol.


location = "";


location.href = "";

Both are used to set the URL. Both are described as running JavaScript 1.0 in the backend in Netscape 2.0 and have been running in all browsers ever since. However, you have the liberty to prefer any one of the two according to your convenience but it is preferred to use location.href because the location might not support older versions of Internet Explorer. 

Commands like location.split(“#); cannot be used as the location is an object but location.href can be used as it is a string. 

Example: The following code demonstrates the DOM Location href property.


    h1 { 
        color: green; 
    h2 { 
        font-family: Impact; 
    body { 
        text-align: center; 
    <h2>Setting location and location.href</h2>
        Click on the button to go
        to designated URL
    <button ondblclick="myhref()">
        Destination URL
    <p id="href"></p>
        function myhref() { 
           location.href =



My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!