How can I copy and paste a document fragment across different documents?
importNode ()[introduced in DOM 2] and adoptNode () [introduced in DOM 3] both can be used to copy and paste a document fragment across different documents. For adoptNode(), the source node is removed from the original document, while for importNode() the source node is not altered or removed from the original document. Here is an example: Document doc1 = new XMLDocument(); Element element1 = doc1.createElement(“foo”); Document doc2 = new XMLDocument(); Element element2 = doc2.createElement(“bar”); element1.appendChild(element2); Since the owner document of element1 is doc1 while that of element2 is doc2 and appendChild() only works within a single DOM tree, you will get WRONG_DOCUMENT_ERR. Solution 1: Using adoptNode from DOM Level 3 Document doc1 = new XMLDocument(); Element element1 = doc1.createElement(“foo”); Document doc2 = new XMLDocument(); Element element2 = doc2.createElement(“bar”); element2 = doc1.adoptNode(element2); element1.appendChild(element2); Solution 2: Using import