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①

浏览器兼容性

另见