1

I couldn't seem to find quite what I'm looking for in any other question. I am wondering if there is a way to clone an object and its DOM nodes. I have tried:

newObj = jQuery.extend(true, {}, oldObj);

but this does not clone any of the nodes, and :

newObj = oldObj.cloneNode(true);

but this does not clone the object that gives the cloned nodes their functionality and stores a large part of information pertaining to the nodes. My intent was to have the original object defined when the page loads, then clone it and hide it, and then be able to clone that object later again.

I have considered just cloning the DOM nodes and then recreating the object each time, but the object is large and takes a lot of code to define all of its properties and methods.

Greg Rozmarynowycz
  • 2,037
  • 17
  • 20

2 Answers2

4

Simply use $(element).clone();

ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
  • 3
    Just to round it out, it's worth [linking to the docs for `.clone()`](http://api.jquery.com/clone) since it's got a couple of relevant optional arguments – Flambino Aug 19 '11 at 06:24
  • That accomplishes basically the same thing as cloneNode(true), only the nodes are copied, none of the object's properties or method's are cloned – Greg Rozmarynowycz Aug 19 '11 at 06:35
  • After reading the documentation, this is because my script only uses limited jquery; the docs specify that to be cloned, any data must have been assigned using .data(), where as I simply used object.property to define my info – Greg Rozmarynowycz Aug 19 '11 at 06:45
  • So you should fix your script. ;) – ThiefMaster Aug 19 '11 at 08:10
2

The proper jQuery way:

// Shallow copy
var newObject = jQuery.extend({}, oldObject);

// Deep copy
var newObject = jQuery.extend(true, {}, oldObject);

And that's straight from the horse's mouth - the horse being John Resig.

Community
  • 1
  • 1
Jens Roland
  • 27,450
  • 14
  • 82
  • 104
  • I tried this, and it is doing exactly what I want, except for that, the original `orginalObj = div`, but `returnedClonedObj = Object{ }`, and I have no div to append to the page – Greg Rozmarynowycz Aug 19 '11 at 17:17
  • 1
    I'm not sure what you mean by `originalObj = div` -- is the original object a DOM node (=also an object)? jQuery objects have a `.get()` method that return the corresponding DOM node - is that it? – Jens Roland Aug 19 '11 at 19:22