Open In App

Get the current URL using jQuery

Last Updated : 14 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The current URL in jQuery can be obtained by using the ‘href’ property of the Location object which contains information about the current URL. The href property returns a string with the full URL of the current page. We can access the value of the href property using two different methods of jQuery.

Using the attr() method

The attr() method can be used to get the value of the href attribute of the current window location by simply passing it to the method in the form of a string.

Syntax:

$(location).attr('href')

Example 1: This example illustrates getting the current site detail using the attr() method in jQuery.

HTML




<!DOCTYPE html>
<html>
 
<head>
    <title>Get current URL using jQuery?</title>
</head>
 
<body>
    <h1 style="color: green">GeeksForGeeks</h1>
    <b>Get current URL using jQuery?</b>
    <p>
          Click on the button below to get the
          current page URL
      </p>
 
    <p> The current URL is: <span class="output"></span></p>
    <button id="btn">Get current </button>
     
    </script>
     
    <script>
    $('#btn').click(function() {
        currLoc = $(location).attr('href');
        document.querySelector('.output').textContent = currLoc;
    });
    </script>
</body>
 
</html>


Output:

Getting the current URL using jQuery

Using the prop() method

The prop() method can also be used to get the current location URL in the same way as the attr() method was used by passing the href property as parameter to it.

Syntax:

$(location).prop('href');

Example: This example illustrates the use of the prop() method to get the current URL of the window location.

HTML




<!DOCTYPE html>
<html>
 
<head>
    <title>Get current URL using jQuery?</title>
</head>
 
<body>
    <h1 style="color: green">GeeksForGeeks</h1>
    <b>Get current URL using jQuery?</b>
    <p>
          Click on the button below to get
          the current page URL
      </p>
 
    <p> The current URL is: <span class="output"></span></p>
    <button id="btn">Get current </button>
     
    </script>
     
    <script>
    $('#btn').click(function() {
        currLoc = $(location).prop('href');
        document.querySelector('.output').textContent = currLoc;
    });
    </script>
</body>
 
</html>


Output:

jQuery is an open-source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous for its philosophy of “Write less, do more”. You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads