简体   繁体   中英

Select elements with data attribute *not* using jQuery

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 (?).

就是这样:

var elements = document.querySelectorAll('[data-mydata]');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM