HTML DOM getAttributeNode() 方法

WBOY
發布: 2023-08-26 13:21:10
轉載
1190 人瀏覽過

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>
登入後複製

輸出

這將產生以下輸出-

HTML DOM getAttributeNode() 方法

##點擊「取得」按鈕時-

HTML DOM getAttributeNode() 方法

在在上面的範例中-

我們先建立了一個錨元素,其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;
}
登入後複製

以上是HTML DOM getAttributeNode() 方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:tutorialspoint.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!