Dark star
Dark star

Reputation: 5822

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>

Upvotes: 10

Views: 44550

Answers (5)

Richie Rizal Amir
Richie Rizal Amir

Reputation: 865

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
}

Upvotes: 1

Web_Designer
Web_Designer

Reputation: 74530

Using the pure JS node.cloneNode:

https://developer.mozilla.org/en-US/docs/Web/API/Node/cloneNode

function multiplyNode(node, count, deep) {
    for (var i = 0, copy; i < count - 1; i++) {
        copy = node.cloneNode(deep);
        node.parentNode.insertBefore(copy, node);
    }
}

multiplyNode(document.querySelector('.box'), 5, true);

Pass true as third argument to multiplyNode to copy child nodes too.

Here's a demo.

Edit:

With ES6 condensed syntax, the above example becomes:

const node = document.querySelector('.box');
[...Array(5)].forEach(_ => node.parentNode.insertBefore(node.cloneNode(true), node));

Upvotes: 14

Abhi
Abhi

Reputation: 4261

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

Upvotes: 3

Mahedi Sabuj
Mahedi Sabuj

Reputation: 2944

Take a look at the fiddle to get your result

https://jsfiddle.net/dcpg4v1c/

$(document).ready(function(){
   for(var i = 0; i< 5; i++)
     $("#dvMain").append("<div class='row'>Test</div>");  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='dvMain'></div>

Upvotes: 5

bugs2919
bugs2919

Reputation: 358

Make use of php with apache server, change the extension from .html to .php and use:

<?php

for ($i = 1; $i <= 10; $i++) {
    echo "<div id='box'></div>";
}

?>

Upvotes: -4

Related Questions