Let's assume that I have ten images with different data-index
but same class
and src
such as:
<img src="images/image.png" class="image" data-index="${index})">
And I want to reach the data-index
of clicked image with eventListener
const image= document.getElementsByClassName('image');
image.forEach(el => el.addEventListener('click', function() {
console.log(el.getAttribute('data-index'));
}));
But, I get the error which says image.forEach is not a function
. How can I solve this? How can I get the data-index
of clicked image. This task needed to be done with eventListener
. It cannot be done with onClick
because some other parts are failing otherwise. Also, these images are printed by using innerHTML in JS code.
So basically, I have images with same attributes but only not data-index
. How can I reach the data-index
of clicked image?