Blog>
Snippets

Cloning and Appending Child Elements

Clone a specific `<div>` with `id='duplicate-me'` and append the clone to another parent element.
// Find the element that we want to clone
var elementToClone = document.getElementById('duplicate-me');

// Clone the element
var clonedElement = elementToClone.cloneNode(true); // 'true' means clone all child nodes and attributes

// Find the parent element where the clone will be appended
var parentElement = document.getElementById('parent-element-id');

// Append the cloned element to the parent element
parentElement.appendChild(clonedElement);
This code locates a div with id 'duplicate-me' and clones it including all its child nodes and attributes. The clone is then appended to another parent element identified by 'parent-element-id'.