在纯 Javascript 中获取元素的属性名称
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29596551/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get attribute name of element in Pure Javascript
提问by Minh Bang
Here is a demo code:
这是一个演示代码:
<div id="demo" myAttribute="ok"></div>
Here are 2 things I want
1) the attribute name, ie: 'myAttribute'.
2) the element that contains the attribute 'myAttribute', ie: the div.
这是我想要的两件事
1) 属性名称,即:'myAttribute'。
2) 包含属性“myAttribute”的元素,即:div。
回答by Paul S.
To get a NodeListof Nodesthat match a selector
获取与选择器匹配的节点的NodeList
var list = document.querySelectorAll('[myAttribute]');
list
will be Array-likebut not inherit from Array. You can loop over it with for
and list.length
list
将是Array-like但不是从Array继承。您可以使用for
和循环遍历它list.length
To get a NamedNodeMapof the attributeson an Element
要获得的NamedNodeMap中的属性上的元素
var nnm = elem.attributes;
nnm
will be Array-likebut not inherit from Array. You can loop over it with for
and nnm.length
nnm
将是Array-like但不是从Array继承。您可以使用for
和循环遍历它nnm.length
To get the valueof an attributeon an Elementuse .getAttribute
要获取元素上的属性值,请使用.getAttribute
var val = elem.getAttribute('myAttribute');
val
will be null
if there is no such attribute
val
null
如果没有这样的属性,将会是
To test the existance of an attributeon an Elementuse .hasAttribute
要测试元素上的属性是否存在,请使用.hasAttribute
var b = elem.hasAttribute('myAttribute');
b
will be a Booleanvalue, true
or false
b
将是一个布尔值,true
或false
回答by whoacowboy
Using jQuery you could do something like this.
使用 jQuery 你可以做这样的事情。
div = $("[myAttribute]");
attrValue = div.attr('myAttribute');
div
would be the jQuery element.attrValue
would be 'ok'
div
将是 jQuery 元素。attrValue
会“好的”