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();
}
Comments
-
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>
withclass = "test1"
. Now how can I remove the original one that is first one? -
Matus over 10 yearstest1 is already a jQuery object, so you don't need to pass it to $() again
-
Bhojendra Rauniyar over 10 yearswhen you click again this will not function. that is the cloned element doesn't have class?
-
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 over 10 yearsYou can always use
end()
. It's pretty handy, but often not used. But you should definitely go withA. Wolff's
comment -
Bhojendra Rauniyar over 10 yearsI tried both method but not what my slider is doing can you post about end() also.
-
eozzy almost 6 yearsThanks, 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?