HTML Anchor hostname Property: Link Hostname

The hostname property of the HTML <a> (anchor) element interface represents a string containing the domain name of the URL. It allows you to programmatically access or modify the hostname part of a link’s URL using JavaScript. This property is particularly useful when dealing with URLs that need to be dynamically manipulated or when extracting specific parts of a URL for processing.

Definition and Purpose

The hostname property gets or sets the hostname portion of the URL associated with an anchor element. The hostname includes the domain name, and optionally, the subdomain.

  • Purpose:
  • To retrieve the hostname of a URL in an anchor element.
  • To set the hostname, thereby modifying the link’s destination.
  • To dynamically manage and manipulate URLs in web applications.

Syntax

Getting the hostname

let hostname = anchorElement.hostname;

Setting the hostname

anchorElement.hostname = "newhostname.com";

Property Values

| Value | Type | Description |
| :——- | :—– | :—————————————- |
| hostname | String | The hostname part of the URL. |

Examples

Basic Usage: Retrieving the Hostname

This example demonstrates how to retrieve the hostname from an anchor element.

<!DOCTYPE html>
<html>
  <head>
    <title>HTML Anchor Hostname - Get</title>
  </head>
  <body>
    <a id="myAnchor_get" href="https://www.example.com/path">Example Link</a>
    <p id="hostnameOutput_get"></p>

    <script>
      const anchor_get = document.getElementById("myAnchor_get");
      const output_get = document.getElementById("hostnameOutput_get");

      const hostname_get = anchor_get.hostname;
      output_get.textContent = "Hostname: " + hostname_get;
    </script>
  </body>
</html>

Output:

Hostname: www.example.com

Setting the Hostname

This example shows how to change the hostname of a link.

<!DOCTYPE html>
<html>
  <head>
    <title>HTML Anchor Hostname - Set</title>
  </head>
  <body>
    <a id="myAnchor_set" href="https://www.example.com/path">Example Link</a>
    <button id="changeHostnameBtn_set">Change Hostname</button>

    <script>
      const anchor_set = document.getElementById("myAnchor_set");
      const changeBtn_set = document.getElementById("changeHostnameBtn_set");

      changeBtn_set.addEventListener("click", function () {
        anchor_set.hostname = "new.example.com";
        alert("Hostname changed to: " + anchor_set.hostname);
      });
    </script>
  </body>
</html>

Clicking the button will change the hostname and display an alert with the updated hostname.

Using hostname with Multiple Anchor Elements

This example retrieves and displays the hostname of multiple anchor elements on the page.

<!DOCTYPE html>
<html>
  <head>
    <title>HTML Anchor Hostname - Multiple</title>
  </head>
  <body>
    <a id="anchor1_multiple" href="https://www.example.com">Example 1</a><br />
    <a id="anchor2_multiple" href="https://www.wikipedia.org">Example 2</a><br />
    <a id="anchor3_multiple" href="https://www.mozilla.org">Example 3</a>

    <ul id="hostnamesList_multiple"></ul>

    <script>
      const anchor1_multiple = document.getElementById("anchor1_multiple");
      const anchor2_multiple = document.getElementById("anchor2_multiple");
      const anchor3_multiple = document.getElementById("anchor3_multiple");
      const hostnamesList_multiple = document.getElementById(
        "hostnamesList_multiple"
      );

      const anchors_multiple = [anchor1_multiple, anchor2_multiple, anchor3_multiple];

      anchors_multiple.forEach((anchor_multiple) => {
        const hostname_multiple = anchor_multiple.hostname;
        const listItem_multiple = document.createElement("li");
        listItem_multiple.textContent = "Hostname: " + hostname_multiple;
        hostnamesList_multiple.appendChild(listItem_multiple);
      });
    </script>
  </body>
</html>

Output:

  • Hostname: www.example.com
  • Hostname: www.wikipedia.org
  • Hostname: www.mozilla.org

Dynamically Updating Hostname Based on User Input

This example shows how to dynamically update the hostname of an anchor element based on user input.

<!DOCTYPE html>
<html>
  <head>
    <title>HTML Anchor Hostname - Dynamic Update</title>
  </head>
  <body>
    <a id="dynamicAnchor_update" href="https://www.example.com">Example Link</a>
    <input type="text" id="hostnameInput_update" placeholder="Enter new hostname" />
    <button id="updateHostnameBtn_update">Update Hostname</button>

    <script>
      const dynamicAnchor_update = document.getElementById("dynamicAnchor_update");
      const hostnameInput_update = document.getElementById("hostnameInput_update");
      const updateBtn_update = document.getElementById("updateHostnameBtn_update");

      updateBtn_update.addEventListener("click", function () {
        const newHostname_update = hostnameInput_update.value;
        dynamicAnchor_update.hostname = newHostname_update;
        alert("Hostname updated to: " + dynamicAnchor_update.hostname);
      });
    </script>
  </body>
</html>

Entering a new hostname in the input field and clicking the “Update Hostname” button will change the link’s hostname.

Handling Edge Cases: Invalid Hostname

This example demonstrates how to handle edge cases such as setting an invalid hostname.

<!DOCTYPE html>
<html>
  <head>
    <title>HTML Anchor Hostname - Invalid</title>
  </head>
  <body>
    <a id="invalidAnchor" href="https://www.example.com">Example Link</a>
    <button id="setInvalidHostnameBtn">Set Invalid Hostname</button>

    <script>
      const invalidAnchor = document.getElementById("invalidAnchor");
      const setInvalidBtn = document.getElementById("setInvalidHostnameBtn");

      setInvalidBtn.addEventListener("click", function () {
        try {
          invalidAnchor.hostname = "invalid hostname";
          alert("Hostname changed to: " + invalidAnchor.hostname);
        } catch (error) {
          alert("Error: Could not set invalid hostname.");
        }
      });
    </script>
  </body>
</html>

Attempting to set an invalid hostname (e.g., a string with spaces) may result in a DOMException. It’s advisable to implement error handling to manage such scenarios gracefully.

Practical Applications

  • Dynamic Link Generation: Creating or modifying links based on user actions or data changes.
  • URL Parsing: Extracting the hostname from a URL for analytics or routing purposes.
  • Content Redirection: Dynamically updating links to redirect users to different domains.
  • Web Crawlers: Extracting hostname information while traversing links on a webpage.

Tips and Best Practices

  • Validation: Before setting the hostname, validate the input to ensure it’s a valid hostname format.
  • Error Handling: Implement error handling to catch exceptions that may occur when setting the hostname.
  • Security: Be cautious when setting the hostname based on user input to avoid potential security vulnerabilities.
  • Readability: Ensure your code is well-documented and easy to understand, especially when manipulating URLs.

Browser Support

The hostname property is widely supported across modern web browsers:

  • Chrome
  • Firefox
  • Safari
  • Edge
  • Opera

Conclusion

The hostname property of the HTML anchor element provides a straightforward way to access and modify the hostname portion of a URL. By understanding its usage and potential edge cases, developers can effectively manage and manipulate links in web applications, creating dynamic and interactive user experiences.