Sat Jan 08 2022·2 min read
Photo by Seth Doyle
To clone an element and change its id:
cloneNode()method to clone the element.
idproperty on the element.
clone.id = 'another-id'.
Here is the HTML for the examples in this article.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div id="box"> <p>Child 1</p> <p>Child 2</p> </div> <script src="index.js"></script> </body> </html>
const box = document.getElementById('box'); // ✅ Clone node and its descendants const clone = box.cloneNode(true); // ✅ Change clone's id clone.id = 'cloned-box'; // 👇️ Add clone to body document.body.appendChild(clone);
We used the
getElementById() method to select the element we want to clone.
We called the cloneNode method on the element.
cloneNode()method returns a duplicate of the node on which it was called.
The only parameter the method takes is whether the node's descendants should be cloned as well.
false, only the node will be cloned, excluding child elements and
We set the
id attribute on the clone to the value of
You might also use the setAttribute method to achieve the same result.
const box = document.getElementById('box'); // ✅ Clone node and its descendants const clone = box.cloneNode(true); // ✅ Change clone's id clone.setAttribute('id', 'cloned-box'); // 👇️ Add clone to body document.body.appendChild(clone);
setAttribute method takes 2 parameters:
name- the name of the attribute whose value is to be set.
value- the value to assign to the attribute.
The last step is to use the appendChild method to add the element to the DOM.
In the example, we called the method on the
body, however it can be called on
appendChild method adds a node to the end of the list of children of the
element it was called on.
cloneNodemethod does not copy event listeners that were added using the
addEventListener()method and events assigned to element properties, e.g.
box.onclick = function().
If I load the page with the code from the example, I can see that the
element was cloned and its
id has been changed successfully.
I'll send you 1 email a week with links to all of the articles I've written that week