Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to repeat div element n times in HTML?

How can I duplicate a <div> so there are n copies using JavaScript?

Start with 1:

<div class="box"></div>

End up with 5:

<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
like image 703
Sajad Avatar asked May 15 '15 20:05

Sajad


People also ask

How do you repeat a div in HTML?

Add the repeat-element attribute to the element you want to duplicate and specify the number of times to copy. Use the repeat-text attribute if you only want to duplicate the text within the element.

How do you make something repeat in HTML?

Use the <span> element instead. There's no <repeat> tag in HTML, unless you use JavaScript to create such an element in order to select that in CSS.


2 Answers

im using jquery here. You can place div parent as i used in example "divRepeat"

<div id="divRepeat">
   <div class="box"></div>
</div>

in Jquery

for(var i=0;i<("how many repeat do you want");i++){
   $("#divRepeat").append($(".box").html());
   //you can add other logic here, like you want diferent id or class to add in new box
}
like image 134
Richie Rizal Amir Avatar answered Sep 24 '22 02:09

Richie Rizal Amir


Create a container div with a id and place <div class="box"></div> inside it. Then using jQuery you can run a loop for desired number of time and append divs like

jQuery("#container_div_id").append(jQuery("#container_div_id").children().first().clone())

Check fiddle

like image 42
Abhi Avatar answered Sep 24 '22 02:09

Abhi