files/en-us/web/api/document/importnode/index.md
{{APIRef("DOM")}}
The importNode() method of the {{domxref("Document")}} interface creates a copy of a {{domxref("Node")}} or {{domxref("DocumentFragment")}} from another document, to be inserted into the current document later.
The imported node is not yet included in the document tree. To include it, you need to call an insertion method such as {{domxref("Node.appendChild", "appendChild()")}} or {{domxref("Node.insertBefore", "insertBefore()")}} with a node that is currently in the document tree.
Unlike {{domxref("document.adoptNode()")}}, the original node is not removed from its original document. The imported node is a clone of the original.
The {{domxref("Node.cloneNode()")}} method also creates a copy of a node. The difference is that importNode() clones the node in the context of the calling document, whereas cloneNode() uses the document of the node being cloned. The document context determines the {{domxref("CustomElementRegistry")}} for constructing any custom elements. For this reason, to clone nodes to be used in another document, use importNode() on the target document. The {{domxref("HTMLTemplateElement.content")}} is owned by a separate document, so it should also be cloned using document.importNode() so that custom element descendants are constructed using the definitions in the current document. See the {{domxref("Node.cloneNode()")}} page's examples for more details.
importNode(externalNode)
importNode(externalNode, deep)
externalNode
deep {{optional_inline}}
false,
which controls whether to include the entire DOM subtree
of the externalNode in the import.
deep is set to true, then
externalNode and all of its descendants are copied.deep is set to false, then only
externalNode is imported — the new node has no children.The copied importedNode in the scope of the importing document.
[!NOTE]
importedNode's {{domxref("Node.parentNode")}} isnull, since it has not yet been inserted into the document tree!
const iframe = document.querySelector("iframe");
const oldNode = iframe.contentWindow.document.getElementById("myNode");
const newNode = document.importNode(oldNode, true);
document.getElementById("container").appendChild(newNode);
Before they can be inserted into the current document, nodes from external documents should either be:
document.importNode(); or[!NOTE] Although Firefox doesn't currently enforce this rule, we encourage you to follow this rule for improved future compatibility.
For more on the {{domXref("Node.ownerDocument")}} issues, see the W3C DOM FAQ.
{{Specifications}}
{{Compat}}