7

I am trying to use jquery appendTo in order to copy an element into another container. The object is indeed appended but, it is removed from the source. Is there a way I can append the element while leaving the source element where it is? call it copy call it clone call it whatever you feel like.

Here is my current code:

jQuery(document).ready(function()
{
    jQuery('#button').appendTo('#panel'); //button should appear ALSO in panel.
});
Shimmy Weitzhandler
  • 101,809
  • 122
  • 424
  • 632
  • Ended up here and found out I was really looking for `detach()` instead of `clone`. `detach` removes the item from the DOM but retains data bindings so event handlers will still work when you `append` the element somewhere else. http://api.jquery.com/detach/ – Dylan Valade Jan 12 '15 at 00:22

3 Answers3

12

Close, but not close enough. The code below will clone() the element and then append it in #panel.

jQuery(document).ready(function()
{
    jQuery('#button').clone().appendTo('#panel');
});

Note that it is against standards to have an ID used twice in the same page. So, to fix this:

jQuery(document).ready(function()
{
    jQuery('#button').clone().attr('id', 'newbutton').appendTo('#panel');
});
Andrew Moore
  • 93,497
  • 30
  • 163
  • 175
5

Simply call the clone() method on your selected jQuery object before appending it:

$('#button').clone().appendTo('#panel');

If you need to also clone all the event handlers attached to the selected elements, pass boolean true as a parameter to the clone() method.

Also, you may will want to change the id attribute of the selected element... That is as easy as:

$('#button').clone().attr('id', 'button-clone').appendTo('#panel');
jason
  • 8,918
  • 2
  • 37
  • 43
1

The code you would need to run is:

jQuery(document).ready(function()
{
    jQuery('#button').clone().appendTo('#panel'); //button should appear ALSO in panel.
});

What this does is grabs the node from the DOM and then makes a clone of it in memory. The line then takes this new object (jQuery('#button').clone()) and then appends it back into the DOM at #panel. This is generally always a good strategy: try to do your DOM manipulation by touching the DOM as little as possible. You can do TONS of manipulation of nodes and elements without inserting or appending them till the very end.

daveslab
  • 10,000
  • 21
  • 60
  • 86
  • I know this is really old but have to downvote as the ID gets duplicated which produces invalid HTML. i.e. https://stackoverflow.com/a/25493852/125981 – Mark Schultheiss Jul 12 '18 at 18:43