Reputation: 107
HTML
<button class='button' data-next="games" data-parent="games1" data-storage="128" data-graphcard="2" data-processor="i3">Click here</button>
Js.
let hardware = ["storage", "graphcard", "processor"];
const allButtonsToStore = document.querySelectorAll('.button');
allButtonsToStore.forEach((el, i) => {
el.addEventListener('click', () => {
hardware.forEach((item) => {
console.log(`${el.dataset.item}`);
});
});
});
What I'm trying to do is to get each item from the array and use it to find that data in the html.
${el.dataset.*}
where ' * ' = items of the array.
So: get value of dataset storage, graphcard and processor of the button. This would be ${el.dataset.storage}
, ${el.dataset.graphcard}
and ${el.dataset.processor}
. In order not to write all of the items of the array, I'm trying to get all items in array (hardware.forEach((item)
) and put in ${el.dataset.item}
but since .`${el.dataset.item}`.
is encaptioned by "``" I'm not able to escape after "${el.dataset.
", insert the actual item
and and capture it again in order to send the line with }
I tried things like ${el.dataset."item"}
, ${el.dataset.[item]}
or ${el.dataset.(item)}
but that didn't work.
Upvotes: 0
Views: 18
Reputation: 66218
You're almost getting it correct: the syntactically correct bracket notation is ${el.dataset[item]}
—i.e. without the extra .
between dataset
and [item]
. See proof-of-concept here:
let hardware = ["storage", "graphcard", "processor"];
const allButtonsToStore = document.querySelectorAll('.button');
allButtonsToStore.forEach((el, i) => {
el.addEventListener('click', () => {
hardware.forEach((item) => {
console.log(`${el.dataset[item]}`);
});
});
});
<button class='button' data-next="games" data-parent="games1" data-storage="128" data-graphcard="2" data-processor="i3">Click here</button>
Upvotes: 1