Search code examples
javascriptpropertiesclonenode

Why does cloneNode exclude custom properties?


This is related to the question javascript cloneNode and properties.

I'm seeing the same behaviour. Node.cloneNode does not copy over any properties that I add myself (code from original post):

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

    var theClone = theSource.cloneNode(true);
    alert(theClone.dictator); 

theClone does not contain any property "dictator".

I haven't been able to find any explanation for why this is the case. The documentation on MDN states that cloneNode "copies all of its attributes and their values", a line which is taken directly from the DOM specification itself.

This seems broken to me as it makes it next to impossible to do a deep copy of a DOM tree that contains custom properties.

Am I missing something here?


Solution

  • A property is not equal to an attribute.

    Use setAttribute() and getAttribute() instead.

    var theSource = document.getElementById("someDiv")
    theSource.setAttribute('dictator','stalin');
    
    var theClone = theSource.cloneNode(true);
    alert(theClone.getAttribute('dictator'));