Search code examples
jquerydomclone

Clone jQuery selection into variable and insert it back into DOM


What am i doing wrong, isn't it possible to clone elements into a variable and insert it back into DOM from there?

var clonedElements = $('.source .item').clone();
$('.target .item').each(function(index) {
    $(this).after(clonedElements[0]);
});

Decrease the cloned array by always inserting the first element after a element extisting in target.


Solution

  • Got my mistake:

    $(this).after(clonedElements[0]);
    

    ...doens't remove the element from array and the next elements don't get a new index to be accessable by [0] again, like they would when acting on a jQuery object:

    $(this).after($('.source .item')[0]);
    

    So the solution is to convert the clones to an array and shift on them:

    var items = $(".source .item").clone().toArray();
    $('.target .item').each(function(index) {
        $(this).after(items.shift());                
    });
    

    Example: https://jsfiddle.net/9q6brnkv/