Borislav Hadzhiev
Reading timeยท2 min
Photo from Unsplash
To clone an element and change its id:
cloneNode()
method to clone the element.id
property on the element.clone.id = 'another-id'
.Here is the HTML for the examples.
<!DOCTYPE html> <html lang="en"> <head> <title>bobbyhadz.com</title> <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>
And here is the related JavaScript code.
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 Text
nodes.We set the id
attribute on the clone to the value of cloned-box
.
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);
The 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
any Node
.
The appendChild
method adds a node to the end of the list of children of the
element it was called on.
cloneNode
method 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 div
element was cloned and its id
has been changed successfully.