HTML - DOM href Property



The HTML DOM href property is used to get (retrieve) or set (update) the source URL for an anchor (<a>) element in HTML.

It returns the current URL that the anchor links to and when modified, it updates the href attribute of the anchor, allowing you to change the link destination dynamically.

Syntax

Following is the syntax of the HTML DOM href (to get the href attribute) property −

anchorObject.href

To update (set) the href property, use the following syntax −

anchorObject.href = new_url

Parameters

Since it is a property, it does not accept any parameters.

Return value

This property returns the current URL of the anchor element as a string.

Example 1: Retrieving the URL of an Anchor ("a") Element

The following is the basic example of the HTML DOM href property. It returns the current URL of an anchor element −

<!DOCTYPE html>
<html lang="en">
<head>
<title>HTML DOM href</title>
</head>
<body>
<p>URL of the current link will be displayed below:-</p>
<span>MyLink: </span>
<a href="https://www.tutorialspoint.com/" id="my_link" target="_blank">Welcome to Tutorialspoint</a>
<p>The URL of the above Link: </p><span id="result"></span>
<script>
      let my_url = document.getElementById("my_link");
      document.getElementById("result").innerHTML = my_url.href;
</script>
</body>
</html>

Example 2: Updating the URL of an Anchor ("a") Element

Here is another example of using HTML DOM href property. We use this property to change the current URL of an anchor element −

<!DOCTYPE html>
<html lang="en">
<head>
<title>HTML DOM href</title>
</head>
<body>
<p>Click the button to update the URL of the below link:-</p>
<span>MyLink: </span>
<a href="https://www.tutorialspoint.com/" id="my_link" target="_blank">Click me</a>
<button id="update_btn">Update URL</button>
<p id="result"></p>
<span id="new"></span>
<script>
      document.getElementById("update_btn").addEventListener("click", ()=>{
         let my_url = document.getElementById("my_link");
         document.getElementById("result").innerHTML = "URL has been updated click the above link to verify";
         my_url.href = "https://www.tutorialspoint.com/html/index.htm";
         document.getElementById("new").innerHTML = "Updated URL: " + my_url.href;
      });
</script>
</body>
</html>

Supported Browsers

Property Chrome Edge Firefox Safari Opera
value Yes Yes Yes Yes Yes
html_dom.htm
Advertisements