Search code examples
jqueryhtmlclone

Html structure affecting element cloning


So, I have bunch of elements inside parent elements:

<div class="copyFrom">
    <div class="copyThese">copyThese1</div>
</div>
<div class="copyFrom">
    <div class="copyThese">copyThese2</div>
</div>

Also, I have separate .Parent element in which I append .copyHere elements to correspond the amount of .copyFrom elements

<div class="Parent">
    <div class="copyHere"></div>
    <div class="copyHere"></div>
</div>

Aaaalso, Inside .copyHere I clone every separate .copyThese elements

<div class="Parent">
    <div class="copyHere">
        <div class="copyThese">copyThese1</div>
    </div>
    <div class="copyHere">
        <div class="copyThese">copyThese2</div>
    </div>
</div>

Now, the problem is:

For some reason, if .Parent is below all the .copyFrom elements The .copyThese elements are cloned in just fine.

But.. If .Parent element is above The .copyFrom elements, the cloning of .copyThese elements goes haywire.

I need to have .Parent element both above and below. ( Without weird cloning problems.)

jsfiddle:

http://jsfiddle.net/lollero/mZhUG/2/ - Above - Correct

http://jsfiddle.net/lollero/mZhUG/3/ - Below - Problem


Solution

  • It is because you are adding a new .copyThese element each iteration.

    copyThese.eq( copyHere ).clone().appendTo( $(this) );

    You are cloning the nth element, but you have added n elements above, so even though your indexer is incrementing you are still cloning the same div.

    $('.copyHere').each(function(){
        var copyHere = $(this).index();
    
        // you re-initialise this array within each loop, 
        // elements are added to the start of the array each time
        var copyThese = $('.copyThese');
    
        copyThese.eq( copyHere ).clone().appendTo( $(this) );
    });
    

    change to this and it works:

    copyThese = $('.copyThese');
    
    $('.copyHere').each(function(){
        var copyHere = $(this).index();
        copyThese.eq( copyHere ).clone().appendTo( $(this) );
    });
    

    do you see the difference? I'm maybe not explaining it very well but hopefully you can see the problem.