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


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

HTML DOM getAttributeNode() 用於將給定的元素屬性節點作為 Attr 對象返回。使用各種 Attr 對象屬性和方法,您可以操作屬性。

用法

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

element.getAttributeNode(attributename)

這裏,attributename 是一個字符串類型的強製參數,它指定了我們要返回的屬性名稱。

示例

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

<!DOCTYPE html>
<html>
<head>
<script>
   function getAttrNode(){
      var a = document.getElementsByTagName("a")[0].getAttributeNode("href");
      var val=a.value;
      document.getElementById("Sample").innerHTML = val;
   }
</script>
</head>
<body>
<h1>getAttributeNode() 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="getAttrNode()">GET</button>
<p id="Sample"></p>
</body>
</html>

輸出

這將產生以下輸出 -

單擊“獲取”按鈕 -

在上麵的例子中 -

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

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

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

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

getAttrNode() 方法使用 getElementByTagName() 方法獲取 HTML 文檔中的第一個錨元素。然後它使用參數值為 “href” 的 getAttributeNode(“href”) 方法。

getAttributeNode() 方法返回一個表示 href 屬性的 attr 對象並將其分配給變量 a。然後我們使用 attr 對象 “value” 屬性將 href 屬性值分配給變量 val。獲得的 href 屬性值使用其 innerHTML 屬性顯示在 id “Sample” 的段落中 -

function getAttrNode(){
   var a = document.getElementsByTagName("a")[0].getAttributeNode("href");
   var val=a.value;
   document.getElementById("Sample").innerHTML = val;
}

相關用法


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