views:

508

answers:

3

Hi.

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.
});
+3  A: 

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
+1  A: 

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
+1  A: 

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