Clone an Element and change its ID using JavaScript

avatar

Borislav Hadzhiev

2 min

banner

Photo from Unsplash

# Clone an Element and change its ID using JavaScript

To clone an element and change its id:

  1. Use the cloneNode() method to clone the element.
  2. Set a different id property on the element.
  3. For example, clone.id = 'another-id'.

Here is the HTML for the examples.

index.html
<!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.

index.js
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.

The 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.

If set to 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.

# Clone an element and change its id using setAttribute

You might also use the setAttribute method to achieve the same result.

index.js
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:

  1. name - the name of the attribute whose value is to be set.
  2. value - the value to assign to the attribute.
If the attribute already exists on the element, the value is updated, otherwise, a new attribute is added with the specified name and value.

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.

It should be noted that the 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.

element cloned id changed

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2023 Borislav Hadzhiev