Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create multiple divs using a for loop

This is a really simple question but I don't know why it doesn't work. I have an array with 3 items inside. And I have a container which I would like to insert a number of divs based on the number of items in my array. I used a for loop for this but it is only creating one div. Should it not create 3?

for (var i = 0; i < array.length; i++) {
   var container = document.getElementById("container");
   container.innerHTML = '<div class="box"></div>';
}

here is a fiddle to demonstrate further fiddle

like image 749
Sai Avatar asked Aug 10 '15 12:08

Sai


People also ask

How do I make multiple divs in CSS?

Three or more different div can be put side-by-side using CSS. Use CSS property to set the height and width of div and use display property to place div in side-by-side format. float:left; This property is used for those elements(div) that will float on left side.

Can you have multiple divs?

Creating Web Layout using Div Tag The div tag is a container tag inside div tag we can put more than one HTML element and can group together and can apply CSS for them.

How do I put multiple divs in one line?

By default, if we have multiple div tags it will be displayed one below the other. In othere words, each div will be displayed in a separate line. To display multiple div tags in the same line, we can use the float property in CSS styles. The float property takes left, right,none(default value) and inherit as values.

Can multiple divs have the same class?

Multiple HTML elements can share the same class.


2 Answers

Move container out of the loop, it is not required inside it.

Append the innerHTML in each iteration.

var container = document.getElementById("container");
for (var i = 0; i < array.length; i++) {
   container.innerHTML += '<div class="box"></div>';
}

Edit:

Thanks Canon, for your comments. I also wanted to suggest the same approach as yours, but I got busy in some other work after posting the answer [No excuses :)] Updating 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 involving more lines of code but this will be more efficient and less error-prone than the previous solution.

like image 190
Vivek Jain Avatar answered Sep 22 '22 12:09

Vivek Jain


Replace = to +=

As per the @canon comment, edited answer are below

var innerHTMLString = "";  
forloop {
    innerHTMLString += '<div class="box"></div>';
}
document.getElementById("htmlElements").innerHTML = innerHTMLString
like image 21
Hardik Raval Avatar answered Sep 22 '22 12:09

Hardik Raval