當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


HTML DOM getAttribute()用法及代碼示例

HTML DOM getAttribute() 方法用於獲取或設置與特定 HTML 元素關聯的屬性。如果元素不包含給定的屬性,那麽這將返回 null 或空字符串。

用法

以下是 getAttribute() 方法的語法 -

element.getAttribute(attributename)

這裏,attributename 是字符串類型,是一個強製參數。它表示要獲取其值的屬性名稱。

示例

讓我們看一個 getAttribute() 方法的例子 -

<!DOCTYPE html>
<html>
<head>
<script>
   function getAttr() {
      var a = document.getElementsByTagName("a")[0].getAttribute("href");
      document.getElementById("Sample").innerHTML = a;
   }
</script>
</head>
<body>
<h1>getAttribute() example</h1>
<a href="https://www.google.com">GOOGLE</a>
<p>Get the href attribute value of the above link by clicking the below button</p>
<button onclick="getAttr()">GET</button>
<p id="Sample"></p>
</body>
</html>

輸出

這將產生以下輸出 -

單擊“獲取”按鈕 -

在上麵的例子中 -

我們首先創建了一個錨元素,其 href 屬性值設置為 https://www.google.com -

<a href="https://www.google.com">GOOGLE</a>

然後我們創建了一個按鈕 GET,它將在用戶點擊時執行 getAttr() 方法 -

<button onclick="getAttr()">GET</button>

getAttr() 方法使用文檔對象的 getElementByTagName() 屬性來獲取 HTML 文檔中的第一個 <a> 元素。

然後它使用 getAttribute() 方法獲取 href 屬性值並將該值分配給變量 a。然後使用其innerHTML屬性將該值顯示在id為“Sample”的段落中 -

function getAttr() {
   var a = document.getElementsByTagName("a")[0].getAttribute("href");
   document.getElementById("Sample").innerHTML = a;
}

相關用法


注:本文由純淨天空篩選整理自AmitDiwan大神的英文原創作品 HTML DOM getAttribute() method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。