Element.getAttribute()

分类: 英国365bet娱乐 时间: 2025-10-27 18:17:28 作者: admin 阅读: 4478
Element.getAttribute()

语法

let attribute = element.getAttribute(attributeName);

上面:

attribute 是一个包含 attributeName 属性值的字符串。

attributeName 是你想要获取的属性值的属性名称。

例子

jslet div1 = document.getElementById("div1");

let align = div1.getAttribute("align");

alert(align);

// shows the value of align for the element with id="div1"

备注

当在被标记为 HTML 文档中的一个 HTML 元素上调用此方法时,getAttribute() 会先将其参数转换为小写形式。

当指定的属性不存在于元素上时,所有浏览器(Firefox、Internet Explorer、Opera 最新版本、Safari、Konqueror 以及 iCab 等等)都返回 null,这也是当前 DOM 规范草案规定的。然而,旧的 DOM 3 Core specification 认为此时正确的返回值应该是一个空字符串,一些 DOM 实现环境实现了该行为(behavior)。在 XUL (Gecko) 中,getAttribute 的实现遵从 DOM 3 Core specification,返回一个空字符串。因此,如果一个属性可能不存在于指定的元素上,在调用 getAttribute() 之前,你应该使用 element.hasAttribute() 来检测该属性是否存在。

浏览器兼容性

Loading…

规范

DOM Level 2 Core: getAttribute (introduced in DOM Level 1 Core)

HTML 5: APIs in HTML documents

Help improve MDN

Was this page helpful to you?

Yes

No

Learn how to contribute

This page was last modified on ⁨2024年12月13日⁩ by MDN contributors.

View this page on GitHub • Report a problem with this content

相关文章

“好奇号”探测车登陆火星一周年
为什么大家觉得《海贼王》不好看了?三大核心原因扎心了!
哪些游戏有骑马的,哪些游戏有骑马的游戏