This page was translated from English by the community.Learn more and join the MDN Web Docs community.
Document.importNode()
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since июль 2015 г..
МетодimportNode() объектаDocument создаёт копиюNode илиDocumentFragment из другого документа, для последующей вставки в текущий документ.
Импортированный узел пока ещё не включён в дерево документов. Чтобы добавить его, вам необходимо вызвать один из методов вставки, например,appendChild() илиinsertBefore() с узлом, которыйнаходится в дереве документов.
В отличие отdocument.adoptNode(), исходный узел не удаляется из исходного документа. Импортированный узел является клоном оригинала.
In this article
Синтаксис
var node = document.importNode(externalNode, deep);
- node
Копируемый узел из области видимости импортируемого документа . Свойство
Node.parentNodeузла =null, до тех пор, пока он не будет вставлен в дерево документа.- externalNode
Внешний
NodeилиDocumentFragment, который импортируется в настоящий документ.- deep
Булеан, контролирующий, необходимо ли импортировать всё DOM поддерево узлаexternalNode.
- Еслиdeep установлен в
true,узел externalNode и все его потомки будут скопированы. - Еслиdeep установлен в
false, импортируется толькоexternalNode — новый узел не будет содержать потомков.
- Еслиdeep установлен в
Примечание:In the DOM4 specification,deep was an optional argument with a default value oftrue.
This default has changed in the latest spec — the new default value isfalse. Though it's still an optional argument, you should always provide thedeep argument for backwardand 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
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 usingdocument.importNode() (or adopted usingdocument.adoptNode()) before they can be inserted into the current document. For more on theNode.ownerDocument issues, see theW3C 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.
Спецификации
| Specification |
|---|
| DOM> # ref-for-dom-document-importnode①> |