How to clone a div and change the ID’s of it and all it’s children to be unique with JavaScript?

Sometimes, we want to clone a div and change the ID’s of it and all it’s children to be unique with JavaScript.

In this article, we’ll look at how to clone a div and change the ID’s of it and all it’s children to be unique with JavaScript.

How to clone a div and change the ID’s of it and all it’s children to be unique with JavaScript?

To clone a div and change the ID’s of it and all it’s children to be unique with JavaScript, we can use the cloneNode method.

For instance, we write:

const div = document.createElement('div')
const div2 = div.cloneNode(true)
div2.id = '2'

We call cloneNode with true to do a deep clone of the div.

Then we assign a new id value to by assigning a value to the id property.

Conclusion

To clone a div and change the ID’s of it and all it’s children to be unique with JavaScript, we can use the cloneNode method.