Open In App
Related Articles

How to redirect to a relative URL in JavaScript?

Improve Article
Improve
Save Article
Save
Like Article
Like

This works in the same way as redirecting to any URL in javascript.

  • Approach 1: To redirect to a relative URL in JavaScript you can use
    window.location.href = '/path';

    window.location.href returns the href (URL) of the current page

    Example 1: A simple redirecting program




    <!DOCTYPE html>
    <html>
    <head>
      <script>
        function newLocation() {
            window.location.href="page.html";
        }
      </script>
    </head>
    <body>
      <input type="button" value="Go to new location" onclick="newLocation()">
    </body>
    </html>

    Output:

  • Approach 2: To redirect to a relative url you can use
    document.location.href = '../';

    Both windows.location.href and document.location.href are same.

    Example 2: A simple redirecting program




    <!DOCTYPE html>
    <html>
    <head>
      <script>
        function newLocation() {
            document.location.href="page.html";
        }
      </script>
    </head>
    <body>
      <input type="button" value="Go to new location" onclick="newLocation()">
    </body>
    </html>

    Output:

    NOTE: You can use both methods but for cross browser safety first one is preferred.


Last Updated : 31 Oct, 2019
Like Article
Save Article
Similar Reads
Related Tutorials