How to clone an element in JavaScript

Cloning DOM elements is essential when you need to duplicate existing elements without manually recreating their structure and content. As the creator of CoreUI, a widely used open-source UI library, I’ve implemented element cloning countless times in dynamic component generation. From my 25 years of experience, the most reliable method is using the cloneNode() method with the deep parameter. This approach preserves all attributes, styles, and optionally child elements.

Use cloneNode(true) to create a deep copy of an element including all its children.

const original = document.getElementById('myElement')
const clone = original.cloneNode(true)
clone.id = 'clonedElement'
document.body.appendChild(clone)

The cloneNode(true) method creates a complete copy of the element and all its descendants. The true parameter enables deep cloning, copying child elements as well. After cloning, you should update unique attributes like id to avoid conflicts, then append the clone to your desired parent element.

Best Practice Note:

This is the same reliable approach we use in CoreUI components for duplicating complex UI structures. Remember to update any unique identifiers and event listeners, as they aren’t automatically transferred to the clone.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author

Subscribe to our newsletter
Get early information about new products, product updates and blog posts.

Answers by CoreUI Core Team