Friday, June 12, 2026
HomeLanguagesJavascriptHow to set location and location.href using JavaScript ?

How to set location and location.href using JavaScript ?

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.

Syntax:

location = "https://www.geeksforgeeks.org";

or

location.href = "https://www.geeksforgeeks.org";

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.

HTML




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


Output:

 

RELATED ARTICLES

Most Popular

Dominic
32515 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6897 POSTS0 COMMENTS
Nicole Veronica
12013 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12109 POSTS0 COMMENTS
Shaida Kate Naidoo
7019 POSTS0 COMMENTS
Ted Musemwa
7262 POSTS0 COMMENTS
Thapelo Manthata
6976 POSTS0 COMMENTS
Umr Jansen
6964 POSTS0 COMMENTS