I am running into this problem that I can't understand. I am doing an exercise that uses DOM manipulation in order to create a grid in javascript. I defined a variable, and then included that variable inside a loop. It only created one div, but it printed my console.log 16 times like I asked. So I defined the variable instead directly inside the loop, and that worked all 16 times. Can someone help me understand what concept about scope I do not seem to understand?
This works:
let gridHome = document.getElementById('grid');
let grid = function() {
for (i = 0; i < 16; i++){
console.log('added a div');
let gridBlock = document.createElement('div');
gridBlock.setAttribute('class', 'block');
gridHome.appendChild(gridBlock);
console.log('run it again');
}
}
grid();
This creates only one div but runs all 16 console.logs:
let gridHome = document.getElementById('grid');
let grid = function() {
let gridBlock = document.createElement('div')
for (i = 0; i < 16; i++){
console.log('added a div');
gridBlock;
gridBlock.setAttribute('class', 'block');
gridHome.appendChild(gridBlock);
console.log('run it again');
}
}
grid();
Any help is greatly appreciated, thank you!