Sacha
Sacha

Reputation: 55

getElementByID( i ) in for loop not working

I'm trying to target multiple elements with a specific ID inside of a for loop. Here's my code:

var insMax = document.getElementsByClassName('instagramimg');
    for (var i = 0 ; i < insMax.length; i++) {
      var insIMG = document.getElementById('instagramID'+i);
      insIMG.addEventListener('click' , function() {
        document.getElementById('instagramPopup'+i).classList.remove("hide");
      });
    }

Somehow this doesn't work and I get the error that it can't read getElementById('instagramPopup'+i) because it's null. This part document.getElementById('instagramID'+i) works just fine. When I run the same code, but with document.getElementById('instagramPopup0).classList.remove("hide"); everything works fine. Why does this not work although it should be two times the exact same thing?

Upvotes: 0

Views: 101

Answers (1)

trincot
trincot

Reputation: 350147

Your variable i will have iterated to the end (taking the value insMax.length) by the time the click handler is executed. And so the value of i is not any more what you expected it to be at the time you evaluate 'instagramPopup'+i.

Solve this by creating a separate i instance for each iteration: change var i to let i.

Upvotes: 1

Related Questions