JAVASCRIPT

Duplicate Existing DOM Elements with cloneNode()

Learn to efficiently create duplicates of existing HTML elements, including their content and event listeners, using the `cloneNode()` method in JavaScript DOM manipulation.

// Assume you have the following HTML:
// <div id="originalDiv">
//   <p>Original Paragraph</p>
//   <button id="originalBtn">Click Me</button>
// </div>
// <div id="clonedContainer"></div>

const originalDiv = document.getElementById('originalDiv');
const clonedContainer = document.getElementById('clonedContainer');

if (originalDiv && clonedContainer) {
  // 1. Clone the element deeply (true): includes all children and their content
  const deepClone = originalDiv.cloneNode(true);
  deepClone.id = 'deepClonedDiv'; // Change ID to avoid duplicates
  deepClone.querySelector('p').textContent = 'Cloned Deeply Paragraph';
  deepClone.querySelector('button').textContent = 'Deep Clone Btn';

  clonedContainer.appendChild(deepClone);
  console.log('Deep clone created and appended.');

  // 2. Clone the element shallowly (false): only clones the element itself, not its children
  const shallowClone = originalDiv.cloneNode(false);
  shallowClone.id = 'shallowClonedDiv'; // Change ID
  shallowClone.textContent = 'Shallow clone content'; // Add content directly

  clonedContainer.appendChild(shallowClone);
  console.log('Shallow clone created and appended.');

  // 3. Example with event listeners (note: cloneNode does NOT copy event listeners by default)
  const btnOriginal = originalDiv.querySelector('#originalBtn');
  btnOriginal.addEventListener('click', function() {
    alert('Original button clicked!');
  });

  // The deepClone button will NOT have the event listener unless re-attached.
  const btnDeepClone = deepClone.querySelector('button');
  if (btnDeepClone) {
    btnDeepClone.addEventListener('click', function() {
      alert('Deep cloned button clicked (listener re-attached)!');
    });
  }
}
How it works: This snippet demonstrates how to duplicate existing DOM elements using the `cloneNode()` method. When `true` is passed as an argument, a 'deep' clone is created, copying the element itself along with all its descendants. If `false` (or omitted) is passed, a 'shallow' clone is made, copying only the element itself without its children. It's crucial to remember that `cloneNode()` does not copy event listeners; they must be re-attached to the cloned elements if desired.

Need help integrating this into your project?

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

Hire DigitalCodeLabs