Skip to content Skip to sidebar Skip to footer

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());
}

Solution 2:

Because one element can't be in several places at once. You have to create one new instance for each element that you want to add in the page.


Post a Comment for "Cannot Append Child With For Loop"