# How to clone an element using JavaScript

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Aug 9, 2020, updated Sep 23, 2021. Topics: JavaScript.
Canonical URL: https://attacomsian.com/blog/javascript-dom-clone-an-element

> Learn how to clone a DOM element by using the cloneNode() method in JavaScript.

To clone a [DOM](https://attacomsian.com/blog/getting-dom-elements-javascript) element in JavaScript, you can use the element's `cloneNode()` method. This method creates a copy of the node and returns the clone.

Here is an example:

```javascript
const target = document.querySelector('#intro');

const cloned = target.cloneNode();
```

By default, the `cloneNode` method only clones the target element attributes and their values. 

If you want to deep clone all child elements as well, just pass `true` to `cloneNode()` method as shown below:

```javascript
const cloned = target.cloneNode(true);
```

To [insert the cloned node to the document](https://attacomsian.com/blog/javascript-insert-element), you can use the `appendChild()` or `isnertBefore()` method:

```javascript
// insert element as last child
document.body.appendChild(cloned);

// insert element before another node
target.parentNode.insertBefore(cloned, target);
```
