Cannot Append Child With For Loop
Why i cannot append numerous blocks with this for loop? var di = document.createElement('div'); di.className = 'box'; di.style.width = '100px'; di.style.height = '100px'; for (var
Solution 1:
In your first sample, the same dom element is appended all the time, because it is defined outside the loop. In the second one, you correctly create a new element for each iterations.
If you want, you can create a copy of an exising element by using cloneNode
. The first example could be re-written like:
var di = document.createElement("div");
di.className = 'box';
di.style.width = '100px';
di.style.height = '100px';
for (var i = 0; i < 5; i++) {
document.body.appendChild(di.cloneNode());
}
Post a Comment for "Cannot Append Child With For Loop"