Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

jquery

http://jsfiddle.net/p57hm/

I simply want one more clone on each click. Did i miss something obvious_ Thanks

Script:

$(function(){

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

});

HTML:

<input type="button" value="clone it"/>

<div id="container"></div>

<div class="cloneitem">clone</div>
like image 742
Johan Avatar asked Nov 28 '11 15:11

Johan


People also ask

When using clone () which attribute can create conflict?

clone() has the side-effect of producing elements with duplicate id attributes, which are supposed to be unique. Where possible, it is recommended to avoid cloning elements with this attribute or using class attributes as identifiers instead.

How append clone in jQuery?

Copy/Paste with clone() & append() using jQuery You can copy an element from one place to another using the clone() function in jQuery. First you make a copy using the clone() function then you use the appendTo() function to indicate where you want the copy placed.

What is Clone function in jQuery?

jQuery clone() Method The clone() method makes a copy of selected elements, including child nodes, text and attributes.


2 Answers

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.

like image 171
Niels Avatar answered Oct 12 '22 01:10

Niels


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

use .first():

$('input').click(function(){
    $('.cloneitem').first().clone().appendTo('#container');
});
like image 20
fardjad Avatar answered Oct 12 '22 00:10

fardjad