DEV Community

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

Posted on

7 1

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
document.getElementById("#papa").appendChild(clone);

Enjoy! 😁

These sites explain it way better!

https://www.w3schools.com/jsref/met_node_clonenode.asp
https://developer.mozilla.org/en-US/docs/Web/API/Node/cloneNode

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

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more