What is the best way to clone a XML document in Javascript?
I tried doing
var newDocument = myDocument.cloneNode(true);
but that just returned null. I also considered doing
var newNode = myDocument.documentElement.cloneNode(true);
but that is not enough for my purposes, since this way the new node has the same ownerDocument
as before.
You call the cloneNode() method on the element you want to copy. If you want to also copy elements nested inside it, pass in true as an argument. // Get the element var elem = document. querySelector('#elem1'); // Create a copy of it var clone = elem.
The cloneNode() method of the Node interface returns a duplicate of the node on which this method was called. Its parameter controls if the subtree contained in a node is also cloned or not.
The cloneNode() method creates a copy of a node, and returns the clone. The cloneNode() method clones all attributes and their values. Set the deep parameter to true if you also want to clone descendants (children).
You can do something like the following to clone a XML document:
var newDocument = oldDocument.implementation.createDocument(
oldDocument.namespaceURI, //namespace to use
null, //name of the root element (or for empty document)
null //doctype (null for XML)
);
var newNode = newDocument.importNode(
oldDocument.documentElement, //node to import
true //clone its descendants
);
newDocument.appendChild(newNode);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With