uriah uriah - 5 months ago 31
jQuery Question

How to clone an element and insert it multiple times in one go?

How can I clone an element and insert it 5 times right after each other? This of course is the base statement:

$('.col').clone().insertAfter('.col');


Here's what I need to get:

<div class="col" id="original"> </div>
<div class="col"> </div>
<div class="col"> </div>
<div class="col"> </div>
<div class="col"> </div>
<div class="col"> </div>


The selector doesn't need to be using an unique id, it can also be a class selector.

I could just repeat the base statement four times but there must be a more elegant way?

Answer

Use a loop, like this:

$(document).ready(function() {
    var e = $('.col');
    for (var i = 0; i < 5; i++) {
      e.clone().insertAfter(e);
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="col">clone me...</div>


Put the element in a variable before the loop, otherwise you will run into problems when you get several elements with the same id were your selector to be based on an id (e.g. $("#col1")).

If your selector is using a class, it doesn't cause the same conflicts as duplicate id's, but you should still put the element in a variable before the loop, otherwise you will end up with a lot more elements than you want.

Comments