DEV Community

Cover image for Duplicating elements with the Node.cloneNode() method

Posted on

Duplicating elements with the Node.cloneNode() method

In one of the projects I'm working on, i needed to have new elements containing a lot of elements. I had already created one element and styled it. But i needed the content to be dynamically updated from a .json file.

So, I thought of a way to duplicate that element and give each its own unique content. Using the Node.cloneNode() method.

It's pretty straight foward

First, you declare and assign your node, the element you want to clone

var node = document.querySelector("#element");

Declare your clone

var clone = node.cloneNode([deep])

You can set the [deep] to be true if you want to copy the children of the node

Set to false if you don't

Now, you can append it into your DOM

Enjoy! 😁

These sites explain it way better!

By the way, this is my first post, I apologize for it's awkwardness 🙂

Top comments (0)