Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For loop inside my custom function doesn't work

I'm trying to create a function that uses the number input I got from users to create the same amount of division inside of a container division.However, no matter what the number is, it always creates only 1 div. It seems like the for loop inside my function is being avoided.

I've tried to alter the function, checked number input whether it is defined or undefined.

function createGrid(parameter) {
  for (i = 0; i < parameter * parameter; i++); {
    const div = document.createElement('div');
    newDiv = container.appendChild(div);
    newDiv.setAttribute('class', 'newDiv');
  }
  return newDiv;
}
like image 453
tosyn Avatar asked Dec 22 '22 21:12

tosyn


2 Answers

You have semicolon ; after for loop which is essentially an empty statement.

That is the reason the for loop is not working as expected, and rest of your code is just creating one divider.

Remove the semicolon ; to fix the issue.

like image 106
Nikhil Avatar answered Dec 30 '22 18:12

Nikhil


Additional to Nikhil's answer, here is how I would write it (without using global variables, which is considered to be bad practice in most cases):

function createGrid(parameter) {
  let newDiv;
  for (let i = 0; i < parameter * parameter; i++) {
    newDiv = document.createElement('div');
    newDiv.setAttribute('class', 'newDiv');
    container.appendChild(newDiv);
  }
  return newDiv;
}

If you don't need to return the last div added, just remove the let newDiv; line and put the const keyword back into the first line of the for loop. Also remove the return value then.

function createGrid(parameter) {
  for (let i = 0; i < parameter * parameter; i++) {
    const newDiv = document.createElement('div');
    newDiv.setAttribute('class', 'newDiv');
    container.appendChild(newDiv);
  }
}
like image 26
André Reichelt Avatar answered Dec 30 '22 18:12

André Reichelt