Declaring div variables inside or outside of a loop with appendChild
I started with a simple loop to output “Hello, world!” a few times:
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:
I expected to get five lines of “Hello, world!” but I only got one. Can someone explain why?
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:
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