How to Clone an HTML Element in JavaScript?

In JavaScript, you can clone an HTML element by using the Node.cloneNode() method, for example, like so:

<div id="my-element">
    <p>foo</p>
    <p>bar</p>
</div>
const elem = document.getElementById('my-element');
const clonedElem = elem.clone(true);

// ...

Passing true to the clone() method indicates that all child and text nodes of the original element should be cloned along with it as well. If you pass false instead, then any text or children that the element contains, are not cloned.

Once you have the cloned node, you can do what you want with it. For example, you can use it to replace an existing element, or append it to a container in the DOM.

If you add the cloned item into DOM, then be aware that if the original element has an id, a name attribute, or other unique attributes, they will all be cloned as is, leading to duplicates. Therefore, you should modify the clone's unique attributes, wherever applicable.


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.