Javascript DOM HTML Node cloneNode Method

Introduction

Copy a <li> element from one list to another:

Click the button to copy an item from one list to another.

View in separate window

<!DOCTYPE html>
<html>
<body>

<ul id="myList1"><li>CSS</li><li>HTML</li></ul>
<ul id="myList2"><li>SQL</li><li>Java</li></ul>
<button onclick="myFunction()">Test</button>
<script>
function myFunction() {/*from   w w w .  j  a  va 2 s. c  o  m*/
  var itm = document.getElementById("myList2").lastChild;
  var cln = itm.cloneNode(true);
  document.getElementById("myList1").appendChild(cln);
}
</script>

</body>
</html>

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

The cloneNode() method clones all attributes and their values.

We can then use the appendChild() or insertBefore() method to insert the cloned node to the document.

Set the deep parameter value to true to clone all children elements, otherwise false.

cloneNode(deep);

Parameter Values

Parameter
Type
Description
deep



Boolean



Optional.
Sets 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

The cloneNode() method returns a Node object representing the cloned node.




PreviousNext

Related