Issue
I am working on a Editor and want to clone a HTML Node with custom properties using JavaScript. I only found a way using setAttribute() but it converts my custom attribute into a string:
// Using custom attributes
var html = document.createElement("div");
var obj = {test: 123,html: html};
html.obj = obj;
var cloned = html.cloneNode(true);
console.log(cloned.obj); // returns null
// Using setAttribute
var html = document.createElement("div");
var obj = {test: 123, html: html};
html.setAttribute("obj") = obj;
var cloned = html.cloneNode(true);
console.log(cloned.getAttribute("obj")); // returns "[object Object]"
How do I clone the html element with the object?
Solution
Attributes in HTML are string values, not JavaScript Objects and JavaScript Properties. The cloneNode
operation only clones HTML intrinsics and not anything you add on top, it is not the same thing as a deep object copy.
You will need to do it manually:
function cloneCustomNode(node) {
var clone node.cloneNode(); // the deep=true parameter is not fully supported, so I'm not using it
clone.obj = node.obj; // this will copy the reference to the object, it will not perform a deep-copy clone of the 'obj' object
return clone;
}
This can be generalised to copy any custom JavaScript properties from one object to another, excluding those already defined in the default (defaultNode
).
var defaultNode = document.createElement("div");
function cloneNodeWithAdditionalProperties(node) {
var clone node.cloneNode();
for(var propertyName in node) {
if( !( propertyName in genericNode ) ) {
clone[ propertyName ] = node[ propertyName ];
}
}
return clone;
}
cloneNodeWithAdditionalProperties
will run in O( n )
time because the if( x in y )
operation is a hashtable lookup with O( 1 )
complexity (where n
is the number of properties).
Answered By - Dai
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.