Filip Huysmans Filip Huysmans - 1 month ago 7
Javascript Question

Use data attr value to get other data attr value

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?

Answer

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>

Comments