Move container from the loop, it is not necessary.
Attach innerHTML to each iteration.
var container = document.getElementById("container"); for (var i = 0; i < array.length; i++) { container.innerHTML += '<div class="box"></div>'; }
Edit:
Thanks to Canon for your comments. I also wanted to suggest the same approach as yours, but I did some other work after posting the answer [No excuse :)] Update the answer:
var htmlElements = ""; for (var i = 0; i < array.length; i++) { htmlElements += '<div class="box"></div>'; } var container = document.getElementById("container"); container.innerHTML = htmlElements;
This may look like including more lines of code, but it will be more efficient and less error prone than the previous solution.
Vivek jain
source share