published: 24 Sep 2022
2 min read
How to clone an element using JavaScript
To clone a DOM 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:
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:
const cloned = target.cloneNode(true);
To insert the cloned node to the document, you can use the appendChild()
or isnertBefore()
method:
// insert element as last child
document.body.appendChild(cloned);
// insert element before another node
target.parentNode.insertBefore(cloned, target);
Are we missing something? Help us improve this article. Reach out to us.
How to clone an element using JavaScript
To clone a DOM 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:
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:
const cloned = target.cloneNode(true);
To insert the cloned node to the document, you can use the appendChild()
or isnertBefore()
method:
// insert element as last child
document.body.appendChild(cloned);
// insert element before another node
target.parentNode.insertBefore(cloned, target);
Are you looking for other code tips?
JS Nooby
Javascript connoisseur