This is a memo about how to add addEventListener for each element with a for loop in JavaScript. Use [].forEach.call. Below is an example.
for (i = 0; i < document.getElementsByTagName('img').length; i++){
document.getElementsByTagName('img')[i].addEventListener("mouseover", function(){
console.log(document.getElementsByTagName('img')[i].src)
});
}
↓
window.addEventListener('DOMContentLoaded', function(e){
[].forEach.call(document.querySelectorAll('img'),function(x){
x.addEventListener("mouseover", function(e){
console.log(e.target.src);
});
});
});
or
// window.addEventListener('DOMContentLoaded', function(e){
[].forEach.call(document.querySelectorAll('img'),function(x){
x.addEventListener("mouseover", function(e){
console.log(e.target.src);
});
});
// });
ref:
JavaScript - forループで要素ごとにaddEventListenerを追加したいがうまくいかない(135762)|teratail