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?
The cloneNode() method creates a copy of a node, and returns the clone. The cloneNode() method clones all attributes and their values. Set the deep parameter to true if you also want to clone descendants (children).
to add the div. Then we can clone the div by writing: const div = document. getElementById('foo') const clone = div.
The . clone() method performs a deep copy of the set of matched elements, meaning that it copies the matched elements as well as all of their descendant elements and text nodes.
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.
<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?
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With