JAVASCRIPT

Duplicate an Element with `cloneNode`

Learn to create a copy of an existing HTML element, including its content and children, using JavaScript's `cloneNode()` method for dynamic content generation and template reuse.

function cloneElement(originalElementId, deepClone = true) {
  const originalElement = document.getElementById(originalElementId);
  if (!originalElement) {
    console.error(`Original element with ID '${originalElementId}' not found.`);
    return null;
  }

  // cloneNode(true) performs a deep clone (includes all descendants)
  // cloneNode(false) performs a shallow clone (only the element itself)
  const clonedElement = originalElement.cloneNode(deepClone);

  // Optionally modify the ID to prevent duplicates if appending to the same document
  if (clonedElement.id) {
    clonedElement.id = `${clonedElement.id}-cloned-${Date.now()}`;
  }
  // You might also want to clear event listeners or modify other attributes

  console.log('Element cloned:', clonedElement);
  return clonedElement;
}

// Example usage:
// <div id="itemTemplate"><p>Product Name</p><button>Add</button></div>
// const clonedItem = cloneElement('itemTemplate');
// if (clonedItem) {
//   document.getElementById('container').appendChild(clonedItem);
// }
How it works: The `cloneNode()` method creates a duplicate of a node. It takes a boolean argument: `true` for a deep clone (meaning all descendants of the node are also cloned), and `false` for a shallow clone (only the node itself is cloned, without its children). This is incredibly useful for reusing existing HTML structures as templates, allowing you to dynamically create new content based on a pre-defined layout without having to rebuild it from scratch.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs