如何获取JavaScript中元素的属性值? [英] How can I get the attribute value of an element in JavaScript?
问题描述
这是演示代码:
<div id="demo" myAttribute="ok"></div>
这是我想要的两件事
1)属性名称,即: 'myAttribute'。
2)包含属性'myAttribute'的元素,即:div。
Here are 2 things I want
1) the attribute name, ie: 'myAttribute'.
2) the element that contains the attribute 'myAttribute', ie: the div.
推荐答案
var list = document.querySelectorAll('[myAttribute]');
list
将是 Array-类似于,但不能继承自 Array 。您可以使用 for
和 list.length
list
will be Array-like but not inherit from Array. You can loop over it with for
and list.length
To get a NamedNodeMap of the attributes on an Element
var nnm = elem.attributes;
nnm
将是 Array-类似于,但不能继承自 Array 。您可以使用 for
和 nnm.length
nnm
will be Array-like but not inherit from Array. You can loop over it with for
and nnm.length
要获取元素上属性的值,请使用 .getAttribute
To get the value of an attribute on an Element use .getAttribute
var val = elem.getAttribute('myAttribute');
val
将为 null
如果没有这样的 attribute
val
will be null
if there is no such attribute
要测试元素上的属性的存在,请使用 .hasAttribute
To test the existance of an attribute on an Element use .hasAttribute
var b = elem.hasAttribute('myAttribute');
b
将是 Boolean 值, true
或 false
这篇关于如何获取JavaScript中元素的属性值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!