English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Location href attribute

JavaScript Location Object

hrefProperty sets or returns the complete URL of the current page.

Syntax:

Return href attribute:

location.href

Set href attribute:

location.href = URL
var x = location.href;
document.querySelector("#output").innerHTML = x;
Test and See‹/›

Browser compatibility

All browsers fully support the href attribute:

Attribute
hrefIsIsIsIsIs

Attribute value

ValueDescription
URLA string specifying the URL of the link.
Possible values:
  • Absolute URL-An absolute path is a path that starts from the root directory of the file system. It always includes the complete URL of the file (e.g., href="https://www.oldtoolbag.com/html/")

  • Relative URL -Point to a file within the website (e.g., href="/ html /")

  • Anchor URL-Point to an anchor within the page (e.g., location.href ="#empty_element")

  • New protocol -Specify other protocols (e.g.
    location.href="ftp://myftpserver.com",
    location.href="mailto: [email protected]"
    or location.href="file:// host / path /example.txt")

Technical details

Return value:A string representing the entire URL of the page, including the protocol (e.g., https://)

More examples

Set the href value to point to another website:

location.href = "https://www.oldtoolbag.com
Test and See‹/›

Set the href value to point to an anchor within the page:

location.href = "#top";
Test and See‹/›

This example displays all location properties:

var txt = "";
txt += "<p>Host: " + location.host + "</p>";
txt += "<p>Hostname: " + location.hostname + "</p>";
txt += "<p>Href: " + location.href + "</p>";
txt += "<p>Origin: " + location.origin + "</p>";
txt += "<p>Pathname: " + location.pathname + "</p>";
txt += "<p>Protocol: " + location.protocol + "</p>";
txt += "<p>Search: " + location.search + "</p>";
document.write(txt);
Test and See‹/›

Related References

Location Reference:location.host property

Location Reference:location.hostname property

Location Reference:location.pathname property

Location Reference:location.protocol property

JavaScript Location Object