Location Object

Location Object

The Location object contains information about the current URL.

The Location object is a part of the Window object and can be accessed through the window.location property.

Example

Take the user to a new address

Location object properties

Properties Description
hash Set or return the URL (anchor) starting from the hash (#).
host Set or return the hostname and the port number of the current URL.
hostname Set or return the hostname of the current URL.
href Set or return the complete URL.
pathname Set or return the path part of the current URL.
port Set or return the port number of the current URL.
protocol Set or return the protocol of the current URL.
search Set or return the URL (query part) starting from the question mark (?).

Location object methods

Properties Description
assign() Load a new document.
reload() Reload the current document.
replace() Replace the current document with a new one.

Description of Location object

The Location object is stored in the Location property of the Window object, representing the Web address of the document currently displayed in that window. Its href propertyThe complete URL of the document is stored here, while other properties describe various parts of the URL. These properties are very similar to the URL property of the Anchor object (or Area object). When a Location object is converted to a string, the value of the href property is returned. This means you can use the expression location instead of location.href.

However, the Anchor object represents a hyperlink in the document, while the Location object represents the URL (or location) of the document currently displayed by the browser. But the Location object can do much more than that; it can also control the position of the document displayed by the browser. If you assign a URL string containing a URL to the Location object or its href attribute, the browser will load and display the document pointed to by the new URL.

In addition to replacing the current URL with a complete URL using location or location.href, you can also modify part of the URL by assigning values to other properties of the Location object. This will create a new URL, part of which is different from the original URL, and the browser will load and display it. For example, if you set the URL string containing the Location object or its href attribute, the browser will load and display the document pointed to by the new URL. hash propertyThen the browser will jump to a specified location in the current document. Similarly, if search propertyThen the browser will reload the URL with the new query string attached.

In addition to the URL property, the Location object's reload() MethodCan reload the current document,replace() Can load a new document without creating a new history record, that is, the new document will replace the current document in the browser's history list.