Vanilla JavaScript clone a DOM element

β€” 4 minute read

permalink

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 permalink

<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 permalink

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 permalink

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 permalink

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! permalink

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