I have a html structure like this.
<div id='mydiv'>
<span class="tobecloned"> some heavy dom <br/> </span>
<span class="tobecloned"> some heavy dom <br/></span>
<span class="tobecloned" id="last"> last some heavy dom <br/></span>
</div>
Now I want to clone the last span.tobecloned modify this clone and insert all modified clone instances multiple times after the last span.tobecloned.
Modification and insertion will happen in a for loop, I am trying something like this:
lastSpan = $('.tobecloned').last();
cloneHtml = $('.tobecloned').last().clone();
for (i = 0; i < 4; i++) {
// Here I am making enough changes in cloneHtml
console.log(i);
cloneHtml.attr('status', i + 1);
cloneHtml.insertAfter($('.tobecloned').last());
}
Above loop runs 4 times but adds cloned element only once. Here is the demo to reproduce the issue http://jsfiddle.net/illumine/SN4rr/
How can I fix this?
Also notice that I am adding new attributes in the for loop. In practical application I'll be modifying more attribute not just 1 or 2.
Is there a better way to do it?
var $lastSpan = $('.tobecloned').last();
for (i = 0; i < 4; i++) {
var $clone = $lastSpan.clone();
$clone.attr('status', i + 1)
.appendTo($lastSpan.parent());
}
In your for loop, cloneHtml is a jQuery object. If you try to insertAfter() it several times, it will simply move. Use .clone() inside the loop, before every edit.:
lastSpan = $('.tobecloned').last();
for (i = 0; i < 4; i++) {
// Here I am making enough changes in cloneHtml
console.log(i);
cloneHtml = lastSpan.clone();
cloneHtml.attr('status', i + 1);
cloneHtml.insertAfter($('.tobecloned').last());
}
Edit: sorry, cloning twice here... Fixed.
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