Element: getAttribute() 方法

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2015 年 7 月⁩以來,各瀏覽器均已提供此特性。

Element 介面的 getAttribute() 方法返回元素上指定屬性的值。

如果給定的屬性不存在,則返回值將是 null

如果您需要檢查 Attr 節點屬性,可以使用 getAttributeNode() 方法代替。

語法

js
getAttribute(attributeName)

引數

屬性名稱

您想要獲取其值的屬性的名稱。

返回值

如果屬性存在,則包含 attributeName 值的字串,否則為 null

示例

html
<!-- example div in an HTML DOC -->
<div id="div1">Hi Champ!</div>
js
const div1 = document.getElementById("div1");
// <div id="div1">Hi Champ!</div>

const exampleAttr = div1.getAttribute("id");
// "div1"

const align = div1.getAttribute("align");
// null

描述

轉換為小寫

當在標記為 HTML 文件的 DOM 中的 HTML 元素上呼叫時,getAttribute() 會在繼續之前將其引數轉換為小寫。

檢索 nonce 值

出於安全原因,來自非指令碼源(如 CSS 選擇器)的 CSP nonces 和 .getAttribute("nonce") 呼叫會被隱藏。

js
let nonce = script.getAttribute("nonce");
// returns empty string

不要從內容屬性檢索 nonce,而是使用 nonce 屬性。

js
let nonce = script.nonce;

規範

規範
DOM
# ref-for-dom-element-getattribute①

瀏覽器相容性

另見