Movatterモバイル変換


[0]ホーム

URL:


  1. Web
  2. Web APIs
  3. Document
  4. importNode()

Document: importNode() method

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

TheimportNode() method of theDocument interface creates a copy of aNode orDocumentFragment 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 asappendChild() orinsertBefore() with a node thatis currently in the document tree.

Unlikedocument.adoptNode(), the original node is not removed from its original document. The imported node is a clone of the original.

TheNode.cloneNode() method also creates a copy of a node. The difference is thatimportNode() clones the node in the context of the calling document, whereascloneNode() uses the document of the node being cloned. The document context determines theCustomElementRegistry for constructing any custom elements. For this reason, to clone nodes to be used in another document, useimportNode() on the target document. TheHTMLTemplateElement.content is owned by a separate document, so it should also be cloned usingdocument.importNode() so that custom element descendants are constructed using the definitions in the current document. See theNode.cloneNode() page's examples for more details.

Syntax

js
importNode(externalNode)importNode(externalNode, deep)

Parameters

externalNode

The externalNode orDocumentFragment to import intothe current document.

deepOptional

A boolean flag, whose default value isfalse,which controls whether to include the entire DOM subtreeof theexternalNode in the import.

  • Ifdeep is set totrue, thenexternalNode and all of its descendants are copied.
  • Ifdeep is set tofalse, then onlyexternalNode is imported — the new node has no children.

Return value

The copiedimportedNode in the scope of the importing document.

Note:importedNode'sNode.parentNode isnull, since it has not yet been inserted into the document tree!

Examples

Using importNode()

js
const iframe = document.querySelector("iframe");const oldNode = iframe.contentWindow.document.getElementById("myNode");const newNode = document.importNode(oldNode, true);document.getElementById("container").appendChild(newNode);

Notes

Before they can be inserted into the current document, nodes from external documents should either be:

Note:Although Firefox doesn't currently enforce this rule, we encourage you to follow this rule for improved future compatibility.

For more on theNode.ownerDocument issues, see the W3C DOM FAQ.

Specifications

Specification
DOM
# ref-for-dom-document-importnode①

Browser compatibility

See also

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2026 Movatter.jp