Declaring div variables inside or outside of a loop with appendChild

I’m doing some JavaScript practice after a few years without working with it, so I apologize if this is a stupid question.

I started with a simple loop to output “Hello, world!” a few times:

for (i = 0; i < 5; i ++){
  var div = document.createElement("div");
  div.innerHTML = "Hello, world!";
  document.body.appendChild(div);
}

That gave me five lines of “Hello, world!”. I wanted to see if the code would run faster if I moved the variable declaration out of the loop:

var div = document.createElement("div");
div.innerHTML = "Hello, world!";
for (i = 0; i < 5; i ++){
  document.body.appendChild(div);
}

I expected to get five lines of “Hello, world!” but I only got one. Can someone explain why?


solution

In the first snippet, you are creating a new element on each iteration and appending it.

In the second snippet, you are creating a single element, and then essentially moving it five times.

According to MDN:

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. 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.

Therefore, you should clone the element before appending it by using the .cloneNode() method:

var div = document.createElement("div");
div.innerHTML = "Hello, world!";
for (i = 0; i < 5; i ++){
  document.body.appendChild(div.cloneNode(true));
}