Categories
JavaScript Answers

How to Clone HTML Element Objects in JavaScript?

Spread the love

To clone HTML element objects in JavaScript, we can call the cloneNode method with true to clone the element.

For instance, if we have the following element:

<div>  
  hello world  
</div>

Then we can clone the div by writing:

const clone = document.querySelector('div').cloneNode(true);  
console.log(clone)

We call document.querySelector to get the div.

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

So clone would have the cloned div.

By John Au-Yeung

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

Leave a Reply

Your email address will not be published. Required fields are marked *