In this section, we will learn what the Element cloneNode() method is and how to use it in JavaScript.
What is Element cloneNode() Method in JavaScript?
The JavaScript Element cloneNode() method is used to get a clone (copy) of an element and return that as a result.
This copy of an element contains the entire attributes and their values of the target element as well (including inline event listeners). However, if you add an event listener using the addEventListener() method, that won’t be included in the clone element.
Note: using this method, by default, the descendant elements (children and grandchildren) won’t be included in the clone element, but we can use the boolean value true as the argument of the method to add those descendant elements in the clone as well.
You should know that when you clone an element, it will become detached from the current flow of the document! Basically, users won’t see this cloned element on the page!
So you need to somehow add this element to the DOM tree as the child of another element that is currently in the DOM so that it becomes part of the flow and so users can see it then.
Element cloneNode() Method Syntax:
element.cloneNode();
Element cloneNode() Method Parameter
The method takes one argument and that is of type boolean.
If the value is set to true, that means the entire descendant of the target element should be included in the clone result.
If the value is set to false (which is the default value) that means only the element itself should be cloned.
Element cloneNode() Method Return Value
The return value of this method is a clone (copy) of the target element (the one that invoked the method) and its descendant elements (if the argument of the method is set to true, of course).
Example: JavaScript clonenode
See the Pen JavaScript clonenode by Omid Dehghan (@odchan1) on CodePen.
Note that the first list item and its content (the text node) are cloned together! This is because of the value true we’ve set as the argument of this method.
If we skip the value true as the argument and put false instead (or don’t put any value because the default value is false anyway) then only the list item will be cloned and its text content will be skipped as we shall see from the example below now!
Example: JavaScript clone (copy) object
See the Pen JavaScript clone (copy) object by Omid Dehghan (@odchan1) on CodePen.