情况如下:
如果有一堆包含数据属性的图像:data-selected和data-id
<img src="" alt="" data-id="2" title="" class="selected" data-selected="1">
<img src="" alt="" data-id="4" title="" data-selected="0">
<img src="" alt="" data-id="5" title="" class="selected" data-selected="1">
<img src="" alt="" data-id="7" title="" data-selected="0">
我想通过数据选择=&#34; 1&#34;
获取所有元素Atm我试过这个:
var interests = document.querySelectorAll("[data-selected='1']");
一旦元素被收集到var中,我想获得这些元素的所有data-id值。
类似
for (var i = 0; i < interest.length; ++i){
var id += interest[i].attr("data-id") . ";";
}
谁知道如何实现这个目标的更好的角度?
提前致谢。
- 似乎无法在上述主题中找到答案
What do querySelectorAll, getElementsByClassName and other getElementsBy* methods return?
答案 0 :(得分:1)
Array.apply(null, document.querySelectorAll("[data-selected='1']")).
forEach(function (e) { console.log(e.getAttribute('data-id')); });
&#13;
<div data-selected='1' data-id="sel1"></div>
<div data-selected='1' data-id="sel2"></div>
<div data-selected='1' data-id="sel3"></div>
<div data-selected='1' data-id="sel4"></div>
<div data-selected='1' data-id="sel5"></div>
<div data-selected='1' data-id="sel6"></div>
<!-- should not get next -->
<div data-selected='2' data-id="sel7"></div>
&#13;