Javascript DOM HTML Document importNode() Method

Introduction

Return the first <h1> element that appears in another document:

Click the button to get and display the value of the first H1 element in another document.

View in separate window

<!DOCTYPE html>
<html>
<body>

<iframe src="https://www.java2s.com" style="height:380px;width:520px;"></iframe>
<button onclick="myFunction()">Test</button>
<script>
function myFunction() {//from   ww w  .  j a v a 2  s .c o  m
  var frame = document.getElementsByTagName("IFRAME")[0]
  var h = frame.contentWindow.document.getElementsByTagName("H1")[0];
  var x = document.importNode(h, true);
  document.body.appendChild(x);
}
</script>

</body>
</html>

The importNode() method imports a node from another document.

The imported node can be of all node types.

If the second parameter is set to true, the nodes's child nodes will also be imported.

The original node is not removed from the other document.

The imported node is a copy of the original.

document.adoptNode() method removes and imports a node from another document.

element.cloneNode() method can copy a node from the current document.

document.importNode(node, deep);

Parameter Values

Parameter TypeDescription
node Node object Required. The node from another document. Can be of any node type
deep Boolean Required. false will only import the node itself, true will import all child nodes

The importNode() method returns a Node object representing the imported node.




PreviousNext

Related