Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

92
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!