HTML Element .cloneNode() Since: DOM Level 1(1998)
A method that duplicates an HTML element. Passing true clones the element along with all its child elements, while passing false clones only the element itself.
Syntax
// Clone the element including all child elements. var clone = element.cloneNode(true); // Clone only the element itself. var clone = element.cloneNode(false);
Arguments
| Argument | Description |
|---|---|
| true | Clones the HTML element along with all its child elements and text content. This is called a "deep copy." |
| false | Clones only the HTML element itself, without any child elements or text content. This is called a "shallow copy." |
Return Value
Returns the newly cloned HTML element. At this point it has not been added to the DOM, so you need to insert it using a method such as parentElement.appendChild().
Sample Code
<ul id="list"> <li class="item">Item 1</li> </ul>
var list = document.querySelector("#list");
var original = document.querySelector(".item");
// Clone the element with child elements and append it to the list.
var deepClone = original.cloneNode(true);
deepClone.textContent = "Item 2";
list.appendChild(deepClone);
// Clone only the element itself and append it to the list.
var shallowClone = original.cloneNode(false);
shallowClone.textContent = "Item 3";
list.appendChild(shallowClone);
Overview
element.cloneNode() is a method that duplicates an HTML element. Passing true performs a "deep copy" that includes all child elements and text content, while passing false performs a "shallow copy" of the element alone.
The cloned element inherits all attributes and classes from the original. Note that the id attribute is also copied, so be careful to avoid duplicate id values on the page. If needed, use element.setAttribute() to update the id after cloning.
If you add an element that already exists in the DOM via parentElement.appendChild(), it will be moved from its original position. By using element.cloneNode() to create a new copy first, you can place the same content in another location while keeping the original element in place.
Browser Compatibility
1 or earlier ×
5 or earlier ×
6 or earlier ×
Android Browser
37+ ○
4 or earlier ×
Chrome Android
36+ ○
17 or earlier ×
Firefox Android
79+ ○
3 or earlier ×If you find any errors or copyright issues, please contact us.