In this article, we will learn to get the current URL using jQuery, along with understanding their implementation through the examples.
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.
Syntax:
$(location).attr('href')
Example 1: This example illustrates getting the current site detail using 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
Example 2: This example illustrates getting the website details using 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 >
< span class = "output" ></ span >
</ script >
< script >
alert("host = "
+ $(location).attr('host')
+ "\nhostname = "
+ $(location).attr('hostname')
+ "\npathname = "
+ $(location).attr('pathname')
+ "\nhref = "
+ $(location).attr('href')
+ "\nport = " + $(location).attr('port')
+ "\nprotocol = "
+ $(location).attr('protocol'));
</ script >
</ body >
</ html >
|
Output:

Getting the site details using jQuery
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.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!