JavaScript Location object has information about the current URL open in the browser. You can access the Location
object by referencing the location
property of the window
or document
object.
window.location
//OR
location
Note: window.location
and document.location
link to the same Location
object.
JavaScript Location Object Properties
Here are some commonly used properties for the location object:
Property | Description |
---|---|
href | Represents a string specifying the entire URL |
protocol | Represents a String at the beginning of a URL to the first colon(:), which specifies the method of access to the URL, for instance, HTTP: or HTTPS: |
host | Represents a string consisting of a hostname and port Strings, for instance:- www.javascriptstudytonight.com:80 |
hostname | Represents the server name, subdomain, and domain name (or IP address)of a URL, for instance, www.javascriptstudytonight.com |
port | Represents a string specifying the communication port that the server uses, for instance, 80 |
pathname | Represents a String Portion of a URL, specifying how a particular resource can be accessed, for instance: order.CGI |
search | Represents a string beginning with a question mark that specifies any query information in an HTTP URL, for instance, batch=1 |
hash | Represents a string beginning with a hash(#), which specifies an anchor name in an HTTP URL, for instance, #intro |
Location Object Methods
Method | Description |
---|---|
assign() | Loads a new document |
reload() | Reloads the current document |
replace() | Replaces the current document with a new one |
Location object in JavaScript
Simple example properties of Location object.
<!DOCTYPE html>
<html>
<body>
<script>
// Hostname
let x = location.hostname;
console.log(x);
// href
x = location.href;
console.log(x);
// protocol
x = location.protocol;
console.log(x);
// host
x = location.host;
console.log(x);
// pathname
x = location.pathname;
console.log(x);
</script>
</body>
</html>
Output:
Location Object methods refer to the functions created inside the location interface which can be used to perform various operations on the URL like reloading it, changing it, etc.
<!DOCTYPE html>
<html>
<body>
<p>Location Methods example</p>
<button onclick="load1()">assign</button>
<button onclick="load2()">href</button>
<button onclick="load3()">replace</button>
<script>
// assign method
function load1(){
location.assign("https://www.eyehunts.com");
}
// href
function load2(){
location.href="https://www.eyehunts.com";
}
// replace()
function load3(){
location.replace("https://www.eyehunts.com");
}
</script>
</body>
</html>
Do comment if you have any doubts or suggestions on this Js object topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version