Warm tip: This article is reproduced from serverfault.com, please click

Why does cloneNode exclude custom properties?

发布于 2012-08-07 21:17:53

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?

Questioner
Scott Cameron
Viewed
0
Dr.Molle 2012-08-08 05:27:24

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'));