使用数据attr值来获取其他数据attr值

时间:2016-10-05 20:24:19

标签: javascript

情况如下:

如果有一堆包含数据属性的图像: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?

1 个答案:

答案 0 :(得分:1)

&#13;
&#13;
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;
&#13;
&#13;