admin管理员组文章数量:1193317
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.
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.
- 2 For these types of questions, you usually get a better response if you start off with what you've tried and ask a more specific question about the issue you've run into. At the very least, explain why existing solutions (of which there are many) aren't working in your case. A specification document for the code you want isn't quite in the spirit of SO. – JDB Commented Apr 13, 2015 at 1:36
2 Answers
Reset to default 22To get a NodeList of Nodes that match a selector
var list = document.querySelectorAll('[myAttribute]');
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
will be Array-like but not inherit from Array. You can loop over it with for
and nnm.length
To get the value of an attribute on an Element use .getAttribute
var val = elem.getAttribute('myAttribute');
val
will be null
if there is no such attribute
To test the existance of an attribute on an Element use .hasAttribute
var b = elem.hasAttribute('myAttribute');
b
will be a Boolean value, true
or false
Using jQuery you could do something like this.
div = $("[myAttribute]");
attrValue = div.attr('myAttribute');
div
would be the jQuery element.
attrValue
would be 'ok'
本文标签: htmlHow can I get the attribute value of an element in JavaScriptStack Overflow
版权声明:本文标题:html - How can I get the attribute value of an element in JavaScript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738451056a2087485.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论