JAVASCRIPT

Clone an Existing DOM Element

Learn to duplicate HTML elements with JavaScript's cloneNode method, enabling you to create copies for reuse or template-based rendering.

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

  const clonedElement = originalElement.cloneNode(deep);
  // If you want the clone to have a unique ID, modify it here
  // For example: clonedElement.id = originalElementId + '-clone';
  console.log(`Element '${originalElementId}' cloned (deep: ${deep}).`);
  return clonedElement;
}

// Example Usage:
// HTML: <div id="template"><span>Hello</span><button>Click</button></div>
// const shallowCopy = cloneElement('template', false);
// // shallowCopy is <div></div> (no children)
// const deepCopy = cloneElement('template', true);
// // deepCopy is <div><span>Hello</span><button>Click</button></div>
// document.body.appendChild(deepCopy); // Add to the DOM
How it works: This snippet provides a function to create a duplicate of an existing HTML element using `element.cloneNode()`. The `deep` parameter determines whether to clone just the element itself (`false`) or also all its descendants (`true`). This is extremely useful for templating, repeatedly adding complex structures, or creating copies of elements without needing to recreate them from scratch using `document.createElement()`.

Need help integrating this into your project?

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

Hire DigitalCodeLabs