createRange Moves DOM Nodes As Fragments
Select a DOM span with document.createRange, preview it with cloneContents, and move whole node sets with extractContents plus append.
Code
// document.createRange selects a span of the DOM without any user
// selection; cloneContents copies it, extractContents cuts it out
const source = document.querySelector('#source');
const target = document.querySelector('#target');
const range = document.createRange();
range.selectNodeContents(source);
console.log('in range:', range.cloneContents().children.length);
// extractContents removes the range from the tree and hands back a
// DocumentFragment, so moving nodes is append and done
const fragment = range.extractContents();
target.append(fragment);
console.log('source now:', source.children.length);
console.log('target now:', target.children.length);How it works
Demo state sits in top-level bindings: source, target, range, fragment.
Points of care
- The import surface (if any) is all standard library, all versioned with the language itself.
- The snippet leans on
document— browser-only surfaces a bare Node process cannot provide.
Using it
Output lines are prefixed (in range:, source now:, target now:), making each step’s impact easy to trace.
The key statements, annotated
const source = document.querySelector('#source');
const target = document.querySelector('#target');
const fragment = range.extractContents();
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.SemVer Range CheckerCheck whether a semantic version satisfies an npm-style range such as caret, tilde, comparison sets, wildcards, or hyphen ranges.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 createRange Moves DOM Nodes As Fragments 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.