0

I'm trying to loop through 2 groups of HTML elements using querySelectorAll, and apply click handler to matching indices (sorry if that's confusing).

Below is the code.

campaignSelect and campaignDetails each have 6 divs, and what I'm trying to do is, when campaignSelect[i] is clicked, a class added to campaignDetails[i] of the same index.

When I run the below code, I get "Can't read property 'classList' of undefined". This works however, if I use the actual index campaignSelect[0] and campaignDetails[0]. What am I doing wrong in the for loop?

Thanks!

var campaignSelect = document.querySelectorAll(".campaign-select");
var campaignInfo = document.querySelector(".campaign-info-container");
var campaignDetails = document.querySelectorAll(".campaign-details");

for(i=0;i<campaignSelect.length;i++){
    campaignSelect[i].addEventListener("click", function(){
        campaignInfo.classList.add("campaign-info-active");
        campaignDetails[i].classList.add("campaign-details-active");
    });
}
  • 1
    Side note: Unless you've declared `i` somewhere you haven't shown, your code is falling prey to [*The Horror of Implicit Globals*](http://blog.niftysnippets.org/2008/03/horror-of-implicit-globals.html) *(that's a post on my anemic little blog)*. Declare your variables. :-) – T.J. Crowder Mar 07 '17 at 10:11
  • wow thank you TJ, the second time you've saved me! :) –  Mar 07 '17 at 10:58

0 Answers0