CloneNode Deep And Shallow Semantics
cloneNode(false) copies one node, cloneNode(true) copies the subtree; cloned ids get duplicated and listeners never travel with the copy.
Code
// Deep and shallow semantics differ only in subtree depth: false copies
// the element itself, true brings descendants along. Neither copies event
// listeners, and ids travel along, so a clone can collide with the source
const source = document.createElement('div');
source.id = 'card';
source.className = 'panel';
source.innerHTML = '<p class="body">hello</p>';
document.body.append(source);
const shallow = source.cloneNode(false);
const deep = source.cloneNode(true);
console.log('shallow has children:', shallow.children.length);
console.log('deep keeps subtree:', deep.querySelector('.body').textContent);
console.log('deep duplicated the id:', deep.id);
// listeners do not travel with clones: the copy starts with zero handlers
deep.addEventListener('click', () => console.log('clicked clone'));
deep.querySelector('.body').textContent = 'hello clone';
console.log('original untouched:', source.querySelector('.body').textContent);
console.log('shallow still childless:', shallow.children.length);How it works
The file’s state is a handful of top-level bindings: source, shallow, deep.
Caveats
- A browser is the runtime here:
documentare not available in Node.
Putting it to use
The run emits 6 labeled sections — shallow has children:, deep keeps subtree:, deep duplicated the id:, clicked clone, original untouched:, shallow still childless: — one per step.
Core lines
deep.querySelector('.body').textContent = 'hello clone';
source.innerHTML = '<p class="body">hello</p>';
const source = document.createElement('div');
Interactive Tools for This Topic
DOM Event Propagation VisualizerVisualize DOM event capturing, targeting, and bubbling phases in real time. Toggle stopPropagation and stopImmediatePropagation to see how events traverse the tree.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- Does CloneNode Deep And Shallow Semantics run in plain Node.js?
- No — it touches `document`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.
Report a problem with this exampleOpens a pre-filled issue on GitHub.