Why my for loop doesn't repeat the div 10 times?

var div = document.getElementById("div");
div.className = "myDiv";
var container = document.getElementById("container");

for (var i = 0; i < 10; i++) {
    container.appendChild(div);
}  

appendChild does not insert copies. You can use cloneNode to make copies.

Node.appendChild()

The Node.appendChild() method adds a node to the end of the list of children of a specified parent node. If the given child is a reference to an existing node in the document, appendChild() moves it from its current position to the new position (there is no requirement to remove the node from its parent node before appending it to some other node).

This means that a node can’t be in two points of the document simultaneously. So if the node already has a parent, the node is first removed, then appended at the new position. The Node.cloneNode() method can be used to make a copy of the node before appending it under the new parent. Note that the copies made with cloneNode will not be automatically kept in sync.

var div = document.getElementById("div");
div.className = "myDiv";
var container = document.getElementById("container");

for (var i = 0; i < 10; i++) {
 container.appendChild(div.cloneNode(true));
}

Just be aware that it will copy the id as well and it is not valid to have the same id more than one time.

2 Likes

super good teaching, so is there any way to get exactly the div repeated 10 times? thanks alot

Not 100% sure what you mean. But you can just account for the div already in the DOM and loop one time less. So you loop 9 times instead of 10 to have 10 divs.

Sure there is, but you don’t want to. You can clone it, but you really want to change the cloned div’s ID each time. say, set it to "div"+i as you loop, so that the new divs get ids that look like div0, div1, … div9

That gives each a unique ID, and it gives you a way to double-check that your loop is working.

Without knowing more about what you are actually doing with the code it is a little hard to give any good advice.

Does it need an id? What is the id used for? Do you actually need a copy, you might not, but we can’t really know because we don’t know what you are using the code for.

no thats good enough for now, I was just looking for some simple way to clone the same div, thanks alot guys it was very useful