admin管理员组文章数量:1392002
Is there a simple way to get a list of all elements containing a data-*
attribute without using jQuery (and hopefully without iterating the whole DOM-tree) ?
I can find a lot of answers using jQuery but I cannot use it in my project and neither can I find answers using plain Javascript.
For example if I have this HTML:
<input data-mydata="data1">
<input data-mydata="data2">
<div data-mydata="data3"></div>
<div data-mydata="data4"></div>
<input>
<div></div>
and then get a list of all elements, of any kind, that contains data-mydata
?
What I try to achieve is to get data from certain elements for storage based on the data-* as well as the data value.
I know I can use the name
attribute with getElementsByName
but that is not possible to use in my project either as the elements have names set for other purposes.
And I believe the querySelectorAll
only works with CSS (?).
Is there a simple way to get a list of all elements containing a data-*
attribute without using jQuery (and hopefully without iterating the whole DOM-tree) ?
I can find a lot of answers using jQuery but I cannot use it in my project and neither can I find answers using plain Javascript.
For example if I have this HTML:
<input data-mydata="data1">
<input data-mydata="data2">
<div data-mydata="data3"></div>
<div data-mydata="data4"></div>
<input>
<div></div>
and then get a list of all elements, of any kind, that contains data-mydata
?
What I try to achieve is to get data from certain elements for storage based on the data-* as well as the data value.
I know I can use the name
attribute with getElementsByName
but that is not possible to use in my project either as the elements have names set for other purposes.
And I believe the querySelectorAll
only works with CSS (?).
- 2 document.querySelectorAll(['data-mydata']); – dandavis Commented Jul 19, 2013 at 18:03
- duplicate question: stackoverflow./questions/9496427/… – bokonic Commented Jul 19, 2013 at 18:03
-
document.querySelectorAll()
is definitely javascript. check out the browser support for it: developer.mozilla/en-US/docs/Web/API/… – pid Commented Jul 19, 2013 at 18:05 - possible duplicate of javascript: select all elements with "data-xxx" attr WITHOUT jQuery – Ja͢ck Commented Jul 19, 2013 at 18:08
- @Jack, thank you. Just removed it. – Sergio Commented Jul 19, 2013 at 18:39
1 Answer
Reset to default 8It's simply this:
var elements = document.querySelectorAll('[data-mydata]');
本文标签: javascriptSelect elements with data attribute *not* using jQueryStack Overflow
版权声明:本文标题:javascript - Select elements with data attribute *not* using jQuery - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744691801a2620039.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论