How to clone an element using JavaScript

published: 24 Sep 2022

2 min read

How to clone an element using JavaScript

To clone a DOM element in JavaScript, you can use the element's cloneNode() method. This method creates a copy of the node and returns the clone.

Here is an example:

const target = document.querySelector('#intro');

const cloned = target.cloneNode();

By default, the cloneNode method only clones the target element attributes and their values.

If you want to deep clone all child elements as well, just pass true to cloneNode() method as shown below:

const cloned = target.cloneNode(true);

To insert the cloned node to the document, you can use the appendChild() or isnertBefore() method:

// insert element as last child
document.body.appendChild(cloned);

// insert element before another node
target.parentNode.insertBefore(cloned, target);

How to clone an element using JavaScript | Coding Tips And Tricks

Are we missing something?  Help us improve this article. Reach out to us.

Are you looking for other code tips?

Check out what's on in the category: javascript, programming
Check out what's on in the tag: javascript, programming