0

Situation as followed:

If have a bunch of images with data attributes: data-selected and 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">

I want to get all elements with data-selected="1"

Atm I tried this with:

var interests = document.querySelectorAll("[data-selected='1']");

Once the elements are gathered in a var I want to get all the data-id values of these elements.

So something like

for (var i = 0; i < interest.length; ++i){
        var id += interest[i].attr("data-id") . ";";
    }

Anyone who knows a better angle on how to achieve this?

Thanks in advance.

-- Can't seem to find an answer in mentioned topic

What do querySelectorAll, getElementsByClassName and other getElementsBy* methods return?

Community
  • 1
  • 1
Filip Huysmans
  • 1,301
  • 1
  • 20
  • 44

1 Answers1

1

Array.apply(null, document.querySelectorAll("[data-selected='1']")).
  forEach(function (e) { console.log(e.getAttribute('data-id')); });
<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>
Keith
  • 22,005
  • 2
  • 27
  • 44