JavaScript Answers

How to Clone a Div and Change its ID with JavaScript?

Spread the love

To clone a div and change its id with JavaScript, we can use the cloneNode method on the div.

Then we can set the id property of the cloned element to set the ID.

For instance, we can write:

<div id='foo'>
  foo bar

to add the div.

Then we can clone the div by writing:

const div = document.getElementById('foo')
const clone = div.cloneNode(true); = "foo2";

We get the div with document.getElementById and assign it to div.

Then we call div.cloneNode with true to clone the div and assign it to clone.

We pass in true to do a deep clone.

Then we set to the ID of the cloned div.

And then we call document.body.appendChild with clone to add to the body.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.