Javascript cloneNode and properties

Is there a quick way to “super” deep clone a node, including its properties? (and methods, I think)

I have something like this:

var theSource = document.getElementById("someDiv")
theSource.dictator = "stalin";

var theClone = theSource.cloneNode(true);

alert(theClone.dictator); 

The new cloned object has no property dictator. Now, let's say I have a thousand properties related to theSource- how can I (implicitly) transfer / copy them to a clone?

// EDIT

@Fabrizio

Your answer is hasOwnPropertynot working properly, so I adjusted it. This is the solution I was looking for:

temp = obj.cloneNode(true);

for(p in obj) {
  if(obj.hasOwnProperty(p)) { eval("temp."+p+"=obj."+p); }
}
0
source share
1 answer

Probably the best way to save many properties is to create a property object in which you can save all properties, for example.

thesource.myproperties = {}
thesource.myproperties.dictator1 = "stalin"; 
thesource.myproperties.dictator2 = "ceasescu"; 
thesource.myproperties.dictator3 = "Berlusconi";
...

then you need to copy only one property

theclone.myproperties = thesource.myproperties

for

for (p in thesource) {
  if (thesource.hasOwnProperty(p)) {
    theclone.p = thesource.p;
  }
}
+2

All Articles