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;
}
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.
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With