Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

93
Vistas
Loop function not firing

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/

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

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.

about 4 years ago · Juan Pablo Isaza Denunciar

0

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.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda