How to remove original element after it was cloned?

15,774

Solution 1

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

Solution 2

$('.clickdiv').on('click', function(){
    var test1 =$('.test1');
    test1.clone().appendTo('#test');
    test1.remove();
}
Share:
15,774
Bhojendra Rauniyar
Author by

Bhojendra Rauniyar

#SOreadyToHelp

Updated on July 29, 2022

Comments

  • Bhojendra Rauniyar
    Bhojendra Rauniyar over 1 year

    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?

  • Matus
    Matus over 10 years
    test1 is already a jQuery object, so you don't need to pass it to $() again
  • Bhojendra Rauniyar
    Bhojendra Rauniyar over 10 years
    when you click again this will not function. that is the cloned element doesn't have class?
  • Arun P Johny
    Arun P Johny over 10 years
    @C-Link because .test1 is already at the bottom of the parent so append does not do anything
  • Jashwant
    Jashwant over 10 years
    You can always use end(). It's pretty handy, but often not used. But you should definitely go with A. Wolff's comment
  • Bhojendra Rauniyar
    Bhojendra Rauniyar over 10 years
    I tried both method but not what my slider is doing can you post about end() also.
  • eozzy
    eozzy almost 6 years
    Thanks, but just don't understand how clone() works AFTER remove(), I thought it would not find anything to clone since, obviously, it has been removed?