JavaScript for loop element addEventListener add

Add Event Listeners for Each Element with for Loop in JavaScript

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.

Shou Arisaka
1 min read
Oct 23, 2025

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

Share this article

Shou Arisaka Oct 23, 2025

🔗 Copy Links