Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery cloneTo instead of appendTo?

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.
});
like image 561
Shimmy Weitzhandler Avatar asked Jul 29 '09 00:07

Shimmy Weitzhandler


2 Answers

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');
});
like image 182
Andrew Moore Avatar answered Oct 09 '22 12:10

Andrew Moore


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');
like image 22
jason Avatar answered Oct 09 '22 13:10

jason