Reputation: 471
I'm trying to create 4 canvas
elements inside several div
's using for
loop inside forEach
.
Here is a sample code:
const wavePart = document.querySelectorAll('.waves');
wavePart.forEach(element => {
for (i; i < 4; i += 1) {
let can = document.createElement('canvas');
element.appendChild(can);
}
});
This code only create the 4 canvas inside the first wavePart
only, it doesn't loop through all containers. Am I doing something wrong?
Upvotes: 1
Views: 5448
Reputation: 1074168
Yes, you're:
Relying on i
being defined by some containing code, and
Not setting an initial value for i
in your loop
Consequently, i
is left at 4
after the first forEach
callback, and so on any subsequent callbacks, the for
loop body never runs because i < 4
is always false at that point.
Instead, declare i
locally within your callback, and set it to 0
to start with:
const wavePart = document.querySelectorAll('.waves');
wavePart.forEach(element => {
for (let i = 0; i < 4; i += 1) {
// ^^^^^^^^^
let can = document.createElement('canvas');
element.appendChild(can);
}
});
Upvotes: 2