Get started with clone CDN

MIT licensed

The Clone library creates deep copies of JS objects or arrays.

Tags:
  • clone
  • object
  • array
  • function
  • date

Stable version

Copied!

How to start using clone CDN


// Include the Clone library from the CDN
const Clone = (function() {
  return (function() {
    function clone(source, target, deep) {
      if (source === null || typeof source !== 'object') {
        return;
      }

      if (target.nodeType) {
        // If target is an existing DOM element, clear it first
        while (target.firstChild) {
          target.removeChild(target.firstChild);
        }
      } else {
        // If target does not exist, create it
        target = document.createElement('div');
      }

      for (const key in source) {
        if (deep && typeof source[key] === 'object') {
          // Recursively clone nested objects
          target[key] = clone(source[key], target[key], deep);
        } else {
          // Copy other properties
          target[key] = source[key];
        }
      }

      return target;
    }

    return { clone };
  })();
})();

// Use the Clone function to create a clone of an element
const originalElement = document.getElementById('original');
const clonedElement = document.createElement('div');

// Clone the original element shallowly (without cloning its children)
const shallowClone = Clone.clone(originalElement);

// Clone the original element deeply (including its children)
const deepClone = Clone.clone(originalElement, clonedElement, true);

// Append the shallow and deep clones to the document
document.body.appendChild(shallowClone);
document.body.appendChild(deepClone);
Copied!
Copied!
Copied!

All versions