Document.importNode() - 外部からノードを複製する
importNode()は、Documentのメソッドです。外部のドキュメントから自身のドキュメントにノードを複製します。元のノードはなくなりません。
概要
- 名前
- importNode
- 所属
- Document
- IDL
[CEReactions, NewObject] Node importNode(Node node, optional boolean deep = false);
- 仕様書
- https://dom.spec.whatwg.org/#dom-document-importnode
説明
第1引数(node)には、対象のノードを指定します。
第2引数(deep)には、子ノードを含めて複製したい場合にtrueを指定します。
ドメインが違う場合、同一オリジンポリシーでセキュリティエラーが発生します。Document.domainの説明をご参考下さい。
デモ
Document.importNode()のデモです。外部ドキュメントの要素を複製します。
<!-- このコードは編集できます。 -->
<!DOCTYPE html>
<html>
<body>
<iframe id="hoge" src="./other-document.html"></iframe>
<p><button id="run">実行</button></p>
<hr>
<script>
document.getElementById( "run" ).onclick = function () {
var iframeElement = document.getElementById( "hoge" ) ;
var sourceNode = iframeElement.contentDocument.getElementById( "source" ) ;
var node = document.importNode( sourceNode, true ) ;
console.log( node ) ;
document.body.appendChild( node ) ;
}
</script>
</body>
</html>
サポート状況
Chrome | Firefox | Safari | Edge | IE | Opera | iOS Safari | Android |
---|---|---|---|---|---|---|---|
● | ● | ● | ● | ● 9+ | ● | ● | ● |
関連記事
- Document.createNodeIterator()
- createNodeIterator()は、Documentのメソッドです。NodeIteratorを新しく作成します。createNodeIterator()とcreateTreeWalker()は、作成するオブジェクトが違うだけで、仕組みは同じです。
- Document.adoptNode()
- adoptNode()は、Documentのメソッドです。外部のドキュメントから自身のドキュメントにノードを移動します。元のノードはなくなります。
- Document.getElementsByName()
- getElementsByName()は、Documentのメソッドです。name属性を指定してノードを取得します。
- Document.getSelection()
- getSelection()は、Documentのメソッドです。選択中のテキストを表すSelectionを返します。