Subscribe

Vanilla JavaScript clone a DOM element

✍️

Guide to explain how to clone an HTML DOM element with Vanilla Javascript. See the code examples in the Codepen!

3 Apr, 2020 Β· 2 min read

You may wonder, why do we want to clone a DOM element?

Let's say we want to build a drag-n-drop editor or a slider. We then need to make clones of HTML elements to achieve that.

So let's learn how to copy an element in JavaScript.

HTML Structure example

<div class="box blue" id="box1">Hi there!</div>

Let's say we need a copy of this div element. We want the id of the cloned element to be unique, e.g. box2, and the color class should be red instead of blue.

The result should look something like below when we are done:

<div class="box blue" id="box1">Hi there!</div>

<div class="box red" id="box2">Hi there!</div>

Clone a DOM element with Vanilla JavaScript

To clone an element, we will first use the most common way to get a specific element by using the querySelector:

let elem = document.querySelector('#box1');

The # is used to indicate an id; we could use a . to indicate a class.

We will now use the JavaScript cloneNode() function. The function accepts true as a parameter if you would like to clone every element inside it.

let elem = document.querySelector('#box1');
let clone = elem.cloneNode(true);

Now we have an identical clone of the element.

Vanilla JavaScript modify a copied object

As mentioned we will be looking into modifying the copy as well:

let elem = document.querySelector('#box1');
let clone = elem.cloneNode(true);

clone.id = 'box2';
clone.classList.remove('blue');
clone.classList.add('red');

elem.after(clone);

As you can see, we modify the id of the box to be box2

Then we use the elements classList (array of all classes) and remove blue from it. Then we append red to the classList.

Finally, we insert the copied element into the DOM after the original element.

Read more about the Vanilla JavaScript classList in this article.

See the code examples in this Codepen

Feel free to play around with this.

See the Pen Vanilla JavaScript clone a DOM element by Chris Bongers (@rebelchris) on CodePen.

Thank you for reading, and let's connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

Spread the knowledge with fellow developers on Twitter
Tweet this tip
Powered by Webmentions - Learn more

Read next πŸ“–

TypeORM viewEntity

30 Mar, 2022 Β· 5 min read

TypeORM viewEntity

The Record Utility Type in TypeScript

12 Mar, 2022 Β· 3 min read

The Record Utility Type in TypeScript

Join 1372 devs and subscribe to my newsletter