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
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>
To clone an element, we will first use the most common way to get a specific element by using the
let elem = document.querySelector('#box1');
#is used to indicate an id; we could use a
.to indicate a class.
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.
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
Then we use the elements
classList (array of all classes) and remove blue from it. Then we append red to the
Finally, we insert the copied element into the DOM after the original element.
See the code examples in this Codepen
Feel free to play around with this.