How to clone a node in JavaScript

cloneNode

To clone a DOM node, we can use the cloneNode method.

Syntax

cloneNode(deepClone);

The cloneNode method takes an argument deepClone. If we send true, it will clone all of its children, including textNode. However, it is false by default, so it will only clone the element in which it is called.

Consider when we have the DOM Node as:

<ul id="user_list" list="true">
  <li> User 1 </li>
  <li> User 2 </li>
  <li> User 3 </li>
  text data
</ul>

But, if we only need to clone ul and not its children, try:

let ul = document.getElementById("user_list");
let clonedNode = ul.cloneNode();

console.log(clonedNode);
// output
<ul id="user_list" list="true">
</ul>

If we need to clone ul and its children, pass true as an argument:

let clonedNode = ul.cloneNode(true);

console.log(clonedNode);

// output 
<ul id="user_list" list="true">
        <li> User 1 </li>
        <li> User 2 </li>
        <li> User 3 </li>
        text data
</ul>

When cloning a Node, all of its properties and attributes are cloned. For example, in the above code, when cloning ul, the cloned node contains the same id as the original Node.

Note :

  • The cloned node will not append the Node to the document – we need to do that.
  • The event attached to the Node will not be copied.
  • If you need events to be cloned, use the jQuery clone method.

Free Resources