0

I'm basically trying to cycle through an array of classes and attach event listeners to each class.

My JS however only attaches an event listener to the last item in the array.

My only guess is that the inner for loop cannot attach eventListeners until the outer loop has finished.

var buttonClasses = ['apple', 'pear'];
var buttonClassElements = []

for (var i = 0; i < buttonClasses.length; i++) {

  var buttonClass = buttonClasses[i];
  buttonClassElements[i] = document.getElementsByClassName(buttonClass);

  var currentElement = buttonClassElements[i];

  // Now cycle through the elements with the current class and add event listeners
  for (var j = 0; j < currentElement.length; j++) {
    currentElement[j].addEventListener('click', function() {
      console.log('Clicked ' + buttonClass);
    });
  }
}
<div class="apple">The Apple</div>
<div class="pear">The Pear</div>
Rajesh
  • 24,354
  • 5
  • 48
  • 79
Modermo
  • 1,852
  • 2
  • 25
  • 46
  • 1
    *"My JS however only attaches an event listener to the last item in the array."* No, but you only ever see the last loop's value for `buttonClass`. The linked question's answers explain why and what to do about it. – T.J. Crowder Apr 04 '17 at 11:49
  • 1
    Simple solution is to use `forEach` on each array instead of `for`. That should fix your problem. – freakish Apr 04 '17 at 11:51
  • I read the linked answer to the question, and it does suggest `forEach`, but also suggest using `let` if the browser permits. Thanks for marking as duplicate :) – Modermo Apr 04 '17 at 11:54
  • 1
    @Modermo Note that `var x = document.getElementsByClassName(...)` does not have `forEach` method. You can emulate it by calling `Array.prototype.forEach(x, function(el) { ... });`. – freakish Apr 04 '17 at 11:56

0 Answers0