To create a deep clone of a Node object in JavaScript, you can use the cloneNode(true)
method inherited from the Node
interface:
var d2 = d.cloneNode(true);
For example:
var d = new DOMParser().parseFromString(
"<root><x><y></y></x></root>",
"text/xml"
);
// Prove it's a deep clone by removing `y` from `x`:
console.log("d before", d.documentElement.firstChild.children.length);
var x = d.documentElement.firstChild;
var d2 = d.cloneNode(true);
x.removeChild(x.firstChild);
console.log("d after", d.documentElement.firstChild.children.length);
console.log("d2 after", d2.documentElement.firstChild.children.length);
Eugene Ryabtsev points out that the prolog information from an XML document is not cloned, which is an important consideration.
The prolog information includes:
- The XML version
- The
standalone
flag
- The encoding
Out of these, only the standalone
flag may be relevant. The version is typically 1.0 as per specifications, and the encoding is less pertinent for an in-memory document. However, if you need to preserve the standalone flag, you can manually copy it after using cloneNode
:
d2.xmlStandalone = d.xmlStandalone;
This will ensure that the standalone flag is also copied over along with the rest of the Node content.