How to get current URL in jQuery?

For getting the current URL in jQuery, you can use the attr() method with the location object or the native JavaScript window.location property. Both methods provide access to the complete URL of the current page.

Methods to Get Current URL

There are two main approaches −

1. Using jQuery's attr() method: $(location).attr('href') returns the complete URL as a string.

2. Using window.location: The native JavaScript window.location object provides access to the current URL and its components.

Example

Here's a complete example demonstrating both methods −

<!DOCTYPE html>
<html>
<head>
    <title>Get Current URL in jQuery</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $("#btn").click(function () {
                // Method 1: Using jQuery attr()
                var url1 = $(location).attr('href');
                alert("Using jQuery attr(): " + url1);
                
                // Method 2: Using window.location
                var url2 = window.location.href;
                alert("Using window.location.href: " + url2);
                
                // Additional location properties
                alert("Protocol: " + window.location.protocol);
                alert("Hostname: " + window.location.hostname);
                alert("Pathname: " + window.location.pathname);
            });
        });
    </script>
</head>
<body>
    <div>
        <button type="button" id="btn">Display URL</button>
    </div>
</body>
</html>

When you click the button, it will display multiple alerts showing the current URL using different methods. The window.location object also provides additional properties like protocol, hostname, and pathname for more specific URL information.

Both methods are reliable for retrieving the current page URL, with window.location.href being the more commonly used approach in modern web development.

Updated on: 2026-03-13T20:51:04+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements