HTML DOM Element getAttributeNode() 方法

定義和用法

getAttribute() 方法返回指定屬性名的屬性值,以 Attr 對象。

替代方案:

使用 getAttribute() 方法 會更容易。

另請參閱:

setAttribute() 方法

hasAttribute() 方法

removeAttribute() 方法

setAttributeNode() 方法

removeAttributeNode() 方法

教程:

HTML 屬性

參考手冊:

HTML DOM Attribute 對象

知識點:getAttribute() 和 getAttributeNode() 的區別

getAttribute() 方法返回屬性的值。

getAttributeNode() 方法返回 Attr 對象,您必須使用 Attr value 屬性 來獲取該值。

結果是相同的。

實例

例子 1

獲取 <h1> 元素的 class 屬性節點的值:

const element = document.getElementsByTagName("H1")[0];
let text = element.getAttributeNode("class").value;

親自試一試

例子 2

獲取 <a> 元素的 target 屬性節點的值:

var elmnt = document.getElementById("myAnchor");
var attr = elmnt.getAttributeNode("target").value;

親自試一試

例子 3

獲取 <button> 元素的 onclick 屬性節點的值:

var elmnt = document.getElementById("myBtn");
var attr = elmnt.getAttributeNode("onclick").value;

親自試一試

語法

element.getAttributeNode(name)

參數

參數 描述
name 必需。屬性的名稱。

返回值

類型 描述
對象 屬性節點的 Attr 對象。
null 如果屬性不存在。

說明

getAttributeNode() 方法將返回一個 Attr 節點,表示指定的屬性的值。注意,通過從 Node 接口繼承的 attributes 屬性也可以獲取該 Attr 節點。

瀏覽器支持

element.getAttributeNode() 是 DOM Level 1 (1998) 特性。

所有瀏覽器都完全支持它:

Chrome IE Edge Firefox Safari Opera
Chrome IE Edge Firefox Safari Opera
支持 9-11 支持 支持 支持 支持