I'm trying to fire a function called NewSquaresInGrid which removes an existing container grid and adds a new container grid containing X amount of divs. The X coming from a prompt.
The old grid container is being removed and a new grid is being added but the contents created via the loop isn't appearing!
Any idea why it's not working?
Code in question:
//Function to be called on button click removing existing grid and replacing with a new one
function refreshGrid() {
newSquares = prompt("How many squares would you like? (Maximum 100)");
removeGrid()
let grid = document.createElement('div');
grid.classList.add('grid');
container.appendChild(grid);
NewSquaresInGrid();
}
function removeGrid() {
container.removeChild(grid);
}
//Add a new grid
function NewSquaresInGrid() {
for (i = 0; i < newSquares; ++i) {
let i = document.createElement('div');
i.classList.add('grid-item');
grid.appendChild(i);
}
}
Full code at: https://jsfiddle.net/ahq6830j/1/
That is because let grid = document.createElement('div'); creates a new grid variable local to the function. So the other functions that try to re-use the grid variable will not have access to it.
remove the let and use grid = document.createElement('div'); to update the already existing global grid variable.
But you revisit the part where you re-use the i variable inside loops.
variables declared with let in javascript is block scoped which basically means that the grid variable declared in refreshGrid() function is not accessible outside the function. One option is to globally declare the grid variable like this:
let grid;
Also you should rename the i in the loop counter to something else so that it does not clash with the other i variable inside the loop.