cloning elements, avoiding more than one clone at a time when adding

Try this http://jsfiddle.net/p57hm/1/

$(function(){

    $('input').click(function(){
        $('.cloneitem:first').clone().appendTo('#container');
    });

});

Currently you are cloning all the elements that have the class .cloneitem but you only want 1 at a time, so you don't want to select all the .cloneItem but just the first one, and clone that one.


$('.cloneitem') selects all elements with cloneitem class.

use .first():

$('input').click(function(){
    $('.cloneitem').first().clone().appendTo('#container');
});

You are cloning an element with class "cloneitem" and then also appending the cloned element with the same class causing issues for the next clone.

$(function() {

    $('input').click(function(){
        $('.cloneitem').first().clone().removeClass('cloneItem').appendTo('#container');
    }); // edited

});

Your clones still have the class cloneitem so are therefore being cloned again. Either remove this class or change the selector so it does not include them.

Something like this, adding the class clones and filtering out those items:

$(function(){
    $('input').click(function(){
        $('.cloneitem').not('.cloned').clone().addClass('cloned').appendTo('#container');
    });    
});

http://jsfiddle.net/infernalbadger/p57hm/4/

Tags:

Jquery