简体   繁体   English

使用jQuery选择具有数据属性* not *的元素

[英]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) ? 有没有一种简单的方法来获取包含data-*属性的所有元素的列表而不使用jQuery(并且希望不迭代整个DOM树)?

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. 我可以使用jQuery找到很多答案,但我不能在我的项目中使用它,也不能使用普通的Javascript找到答案。

For example if I have this HTML: 例如,如果我有这个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 ? 然后获取包含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. 我试图实现的是根据data- *以及数据值从某些元素中获取数据进行存储。

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. 我知道我可以将name属性与getElementsByName一起使用,但由于元素的名称设置用于其他目的,因此无法在我的项目中使用。

And I believe the querySelectorAll only works with CSS (?). 我相信querySelectorAll只适用于CSS(?)。

就是这样:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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