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);

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.