How to clone an element and insert it multiple times in one go?
Solution 1
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.
Solution 2
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('.col').each(function(){
$(this).clone().insertAfter(this);
});
});
</script>
<div class="col">First div </div>
<div class="col">2nd </div>
<div class="col">3rd </div>
<div class="col">4th </div>
<div class="col">5th </div>
is this you looking for?
Solution 3
I wrote a jQuery plug-in:
$.fn.multiply = function(numCopies) {
var newElements = this.clone();
for(var i = 1; i < numCopies; i++)
{
newElements = newElements.add(this.clone());
}
return newElements;
};
This code snippet builds the elements as a jQuery set, instead of adding to the DOM multiple times which can be slow.
Usage:
var li = $('<li>Test</li>');
$('ul').append(li.multiply(4));
So, for your example:
$('.col').multiply(5).insertAfter('.col');
uriah
Updated on May 27, 2020Comments
-
uriah almost 4 years
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?
-
uriah almost 12 yearsThanks Guffa this is perfect!