The code below works as expected.
var mySelector = document.querySelectorAll('.mySelector');
var myFunction = function() {
for (var i = 0; i < mySelector.length; i++) {
mySelector[i].classList.add('myClass');
}
}
However, this code generates an error: "Uncaught TypeError: Cannot read property 'classList' of undefined"
var mySelector = document.querySelectorAll('.mySelector');
var myFunction = function() {
for (var i = 0; i < mySelector.length; i++) {
setTimeout(function(i){
mySelector[i].classList.add('myClass');
}, 1000);
}
}
I'm sure there is a very simple explanation why that is, but I don't know it.
Why?
UPDATE: new code with parameter removed from setTimeout function
var mySelector = document.querySelectorAll('.mySelector');
var myFunction = function() {
for (var i = 0; i < mySelector.length; i++) {
setTimeout(function(){
mySelector[i].classList.add('myClass');
}, 1000);
}
}
UPDATE 2:
Barmar suggested this was an exact duplicate of another question: JavaScript closure inside loops – simple practical example
I grant that it is generically similar and the answer Barmar linked to could probably help someone with more JavaScript experience over the hump I'm facing. But I think my question is different enough to remain open on its own terms for the following reasons: (1) My case is simpler and a correct answer is likely to benefit less skilled JavaScript practitioners such as myself, (2) I'm specifically concerned with setTimeout as it relates to for loops. Again, I'll grant that the answer Barmar referenced could be helpful for many, but it's not particularly helpful for me personally.