HTML - DOM href 屬性



HTML DOM 的href 屬性用於獲取(檢索)或設定(更新)HTML 中錨點(<a>)元素的源 URL。

它返回錨點連結到的當前 URL,並且在修改時,它會更新錨點的 href 屬性,允許您動態更改連結目標。

語法

以下是 HTML DOM 的href(獲取 href 屬性)屬性的語法:

anchorObject.href

要更新(設定)href 屬性,請使用以下語法:

anchorObject.href = new_url

引數

由於它是一個屬性,因此不接受任何引數。

返回值

此屬性將錨元素的當前 URL 作為字串返回。

示例 1:檢索錨點 (“a”) 元素的 URL

以下是 HTML DOM href 屬性的基本示例。它返回錨元素的當前 URL:

<!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://tutorialspoint.tw/" 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>

示例 2:更新錨點 (“a”) 元素的 URL

這是使用 HTML DOM href 屬性的另一個示例。我們使用此屬性更改錨元素的當前 URL:

<!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://tutorialspoint.tw/" 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://tutorialspoint.tw/html/index.htm";
         document.getElementById("new").innerHTML = "Updated URL: " + my_url.href;
      });
</script>
</body>
</html>

支援的瀏覽器

屬性 Chrome Edge Firefox Safari Opera
廣告