How to clone an element and insert it multiple times in one go?
<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?
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.