0

I want my code to give every element with class ddown an event that will ad a slactive class to the actual dropdown. However the console says that document.getElementById('sl'+(n+1)) is null so not an object. But, if I not use n inside the function in event, this works fine, but only for the first element. Elements are named like sl1,sl2,sl3,...

ddown = document.getElementsByClassName('ddown');
for(var n=0; n<ddown.length; n++) {
    ddown[n].addEventListener('mousedown', function(){document.getElementById('sl'+(n+1)).classList.add('slactive');});
    console.log('sl'+(n+1));
}

P.S. console.log gives the right codes, I think the problem is in the scope of n.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
MaxelRus
  • 306
  • 1
  • 10

1 Answers1

2

You need to lock down the value of n before adding the listener.

Replace your line (which is adding the listener) by

(function (n){ ddown[n].addEventListener('mousedown', function(){document.getElementById('sl'+(n+1)).classList.add('slactive');}); )(n)
gurvinder372
  • 66,980
  • 10
  • 72
  • 94