Document.importNode()

Метод importNode() объекта Document создаёт копию Node или DocumentFragment из другого документа, для последующей вставки в текущий документ.

Импортированный узел пока ещё не включён в дерево документов. Чтобы добавить его, вам необходимо вызвать один из методов вставки, например, appendChild() или insertBefore() с узлом, который находится в дереве документов.

В отличие от document.adoptNode() (en-US), исходный узел не удаляется из исходного документа. Импортированный узел является клоном оригинала.

Синтаксис

var node = document.importNode(externalNode, deep);
node

Копируемый узел из области видимости импортируемого документа . Свойство Node.parentNode узла = null, до тех пор, пока он не будет вставлен в дерево документа.

externalNode

Внешний Node или DocumentFragment, который импортируется в настоящий документ.

deep

Булеан, контролирующий, необходимо ли импортировать всё DOM поддерево узла externalNode.

  • Если deep установлен в true, узел externalNode и все его потомки будут скопированы.
  • Если deep установлен в false, импортируется только externalNode — новый узел не будет содержать потомков.

Примечание: In the DOM4 specification, deep was an optional argument with a default value of true.

This default has changed in the latest spec — the new default value is false. Though it's still an optional argument, you should always provide the deep argument for backward and forward compatibility. With Gecko 28.0, the console warns developers not to omit the argument. Starting with Gecko 29.0), a shallow clone is defaulted instead of a deep clone.

Example

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

Notes

Nodes from external documents should be cloned using document.importNode() (or adopted using document.adoptNode() (en-US)) before they can be inserted into the current document. For more on the Node.ownerDocument issues, see the W3C DOM FAQ.

Firefox doesn't currently enforce this rule (it did for a while during the development of Firefox 3, but too many sites break when this rule is enforced). We encourage Web developers to fix their code to follow this rule for improved future compatibility.

Specifications

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

Совместимость с браузерами

BCD tables only load in the browser

See also