Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

100
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda