3

How does one create a copy of a form with all of its form elements so that the copy can be manipulated and the original is left unchanged?

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
reformed
  • 4,505
  • 11
  • 62
  • 88

2 Answers2

7

Using plain javascript cloneNode like this

var dupNode = node.cloneNode(deep);

Example

var p = document.getElementById("para1"),
var p_prime = p.cloneNode(deep); 
//If "deep" is set to true it will clone all the child nodes too,
//If set to false then only the node and not the children

Here is the documentation.

Hope that helps.

woofmeow
  • 2,370
  • 16
  • 13
  • Is `deep` a valid argument? – reformed Aug 12 '13 at 21:02
  • @reformed Yes, `cloneNode` [accepts a parameter](https://developer.mozilla.org/en-US/docs/Web/API/Node.cloneNode). – oleq Aug 12 '13 at 21:04
  • @reformed i have added a link to the docs .. this is plain js just as you wanted. – woofmeow Aug 12 '13 at 21:06
  • Would be nice if you could accept the answer and upvote it .. but only do it if it helped you :) Cheers @reformed . – woofmeow Aug 12 '13 at 21:30
  • @woofmeow I appreciate your help but it would be nice if you'd let me take time away from the computer for other personal things and also to wait for other answers. I already upvoted it, I was planning on accepting your answer. Are you a rep chaser? – reformed Aug 13 '13 at 02:14
  • I am not a "rep chaser" for whatever that mean but sometimes I just like to see if my answer helped the person who asked the question or not. You can even downvote it if you'd like @reformed I wouldn't care. Its just good at times to see a prompt reply. Feel free to downvote too. No issues with me. Have a nice day. – woofmeow Aug 13 '13 at 09:43
  • Just remember that some people aren't always able to give a prompt reply, due to work or whatever else. Asking for votes can be kind of annoying. You might want to take up politics if that's your thing ;) – reformed Aug 13 '13 at 12:17
3

Use the jQuery clone object as such:

var cloned_object = $( ".hello" ).clone().

and to add it to the dom

cloned_object.appendTo( ".goodbye" );

Here is the reference:

http://api.jquery.com/clone/

Smurfette
  • 1,935
  • 2
  • 14
  • 15
  • 1
    Thanks. Any equivalent in vanilla JavaScript? – reformed Aug 12 '13 at 20:59
  • 1
    ... http://stackoverflow.com/questions/122102/most-efficient-way-to-clone-an-object ... this has one – Smurfette Aug 12 '13 at 21:00
  • @Smurfette: No, that's about JavaScript objects in general, not DOM elements. Also from the `javascript` tag description: *"Unless a tag for a framework/library is also included, a pure JavaScript answer is expected."* Please keep that in mind. – Felix Kling Aug 12 '13 at 21:42