Question

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.

Was it helpful?

Solution

Simply use $(element).clone();

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top