CSS
<button class='btn' data-next="games" data-prev="games1" data-storage="128" data-graphcard="2" data-processor="i3">Click Here</button>
JavaScript.
let components = ["storage", "graphcard", "processor"];
const allBtnsToStore = document.querySelectorAll('.btn');
allBtnsToStore.forEach((element, index) => {
element.addEventListener('click', () => {
components.forEach((item) => {
console.log(`${element.dataset.item}`);
});
});
});
The main goal is to retrieve each item from the array and match it with its corresponding data in the HTML.
${element.dataset.*}
where ' * ' represents items in the array.
For instance: access values of dataset storage, graphcard, and processor of the button using ${element.dataset.storage}
, ${element.dataset.graphcard}
, and ${element.dataset.processor}
. Instead of individually specifying all items in the array, I aim to loop through them (components.forEach((item)
) and dynamically replace it in ${element.dataset.item}
However, since .`${element.dataset.item}`.
is encapsulated by "`", escaping after "${element.dataset.
", inserting the actual item
, and re-capturing becomes challenging in order to close the line with }
I experimented with variations like ${element.dataset."item"}
, ${element.dataset.[item]}
, or ${element.dataset.(item)}
but none proved effective.