Element cloneNode Method - Javascript DOM

Javascript examples for DOM:Element cloneNode

Description

The cloneNode() method creates a copy of a node, and returns the clone.

Parameter Values

Parameter TypeDescription
deep Boolean Optional.

deep specifies whether all descendants of the node should be cloned.

  • true - Clone the node, its attributes, and its descendants
  • false - Default. Clone only the node and its attributes

Return Value:

A Node object, representing the cloned node

The following code shows how to copy the div element above, including all its attributes and child elements, and append it to the document

Demo Code

ResultView the demo in separate window

<!DOCTYPE html>
<html>
<body>

<div style="border:1px solid black;background-color:pink">
  <p style="color:red;">A p element</p>
  <p style="color:green;">A p element</p>
  <p style="color:blue;">A p element</p>
</div>/*from w w  w  . j av a2 s. co m*/

<button onclick="myFunction()">Test</button>

<script>
function myFunction() {
    var elmnt = document.getElementsByTagName("DIV")[0];
    var cln = elmnt.cloneNode(true);
    document.body.appendChild(cln);
}
</script>

</body>
</html>

Related Tutorials