How to Clone an HTML Element in JavaScript?

Estimated read time 1 min read

You can clone an HTML element in JavaScript using the cloneNode() method. Here’s an example:

// Select the element you want to clone
const originalElement = document.getElementById('my-element');

// Clone the element
const clonedElement = originalElement.cloneNode(true);

// Append the cloned element to the document

In this example, cloneNode(true) creates a deep clone of the original element, which includes all of its child nodes. If you only want to clone the element itself and not its children, you can pass false as the argument to cloneNode().

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply