Skip to content Skip to sidebar Skip to footer

Issue While Avoiding Foreach Loop

This is an extension to my previous question javascript dynamically adding and removing classes As per the answer given, it uses a forEach loop but I am trying to use a for loop an

Solution 1:

You are running into the classic "closure inside loop" issue, where your loop index variable is the same between all the closure you are creating inside the loop (the functions you are creating as event handlers).

The solution is to wrap the event handler function in an immediately invoked function expression to which you pass the index variable, binding its current value to scope.

functiontest() {
  var paragraphs = document.querySelectorAll("#divid p");
  for (index = 0; index < paragraphs.length; index++) {
    paragraphs[index].addEventListener('click', (function(index) {
      returnfunction() {
        var i;
        for (i = 0; i < index; ++i) {
          paragraphs[i].classList.remove('active');
        }
        for (i = index; i < paragraphs.length; ++i) {
          paragraphs[i].classList.add('active');
        }
      }
    })(index));
  }
}

test();
p.active {
  color: red;
}
<divid="divid"><p>p1</p><p>p2</p><p>p3</p><p>p4</p><p>p5</p><p>p6</p></div>

Post a Comment for "Issue While Avoiding Foreach Loop"