Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to modify a jquery html clone and insert multiple times after a node?

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?

like image 522
ʞɹᴉʞ ǝʌɐp Avatar asked Mar 04 '26 03:03

ʞɹᴉʞ ǝʌɐp


2 Answers

var $lastSpan = $('.tobecloned').last();
for (i = 0; i < 4; i++) {
    var $clone = $lastSpan.clone();
    $clone.attr('status', i + 1)
          .appendTo($lastSpan.parent());
}
like image 148
A. Wolff Avatar answered Mar 05 '26 17:03

A. Wolff


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.

like image 38
Maxim Kumpan Avatar answered Mar 05 '26 17:03

Maxim Kumpan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!