Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85545

How to remove original element after it was cloned?

HTML:

<div id="test">
    <p class="test1">test 1</p>
    <p class="test2">test 2</p>
    <p class="test3">test 3</p>
    <p class="test4">test 4</p>
</div>

<div class="clickdiv">click</div>

jQuery

$('.clickdiv').on('click', function(){
    $('.test1').clone().appendTo('#test');
}

This will result one more <p> with class = "test1". Now how can I remove the original one that is first one?

Upvotes: 8

Views: 17251

Answers (3)

S&#233;bastien Gicquel
S&#233;bastien Gicquel

Reputation: 4386

You don't need to remove the element because appendTo will copy and "remove" it.

You can simply do :

$('.test1').appendTo('#test'); 

Upvotes: 0

trrrrrrm
trrrrrrm

Reputation: 11812

$('.clickdiv').on('click', function(){
    var test1 =$('.test1');
    test1.clone().appendTo('#test');
    test1.remove();
}

Upvotes: 2

Arun P Johny
Arun P Johny

Reputation: 388316

I don't know why you can't just append the element to the parent, instead of cloning it then removing it.

Anyway

$('.test1').remove().clone().appendTo('#test');

Demo: Fiddle

If you want to copy the data and handlers associated with test1 to the clone then @ra_htial with a minor change have to be used

$('.clickdiv').on('click', function () {
    var $el = $('.test1');
    $el.clone(true).appendTo('#test');
    $el.remove();
});

Demo: Fiddle

Upvotes: 21

Related Questions