Vanilla JavaScript clone a DOM element

— 4 minute read

permalink

You may wonder, why do we want to clone a DOM element, but you might see more use for this than initially thought. Let's say we want a Drag-n-drop editor or a slider. We then need to makes clones to use.

HTML Structure example permalink

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

Let's say we need a copy of this box, of course, we want the new id to be unique let's say box2 and the color class to be red instead of blue.

It should look something like this when we are done:

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

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

Cloning a DOM object with Vanilla JavaScript permalink

We will use the most common way to get a specific element with 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. This function accept true as a paramater if you would like to clone every element inside it as well.

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

Now we have an identical clone.

Vanilla JavaScript modify a cloned object permalink

As mentioned we will be looking into modified this cloned object.

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.

Read more about the Vanilla JavaScript classList in this article.

Feel free to play with this Codepen.

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