before, after And replaceWith Edit Nodes
before, after, replaceWith, and remove edit the tree around a node directly: insertions anchor to siblings and removal needs no parent reference.
Code
if (typeof document === 'undefined') {
console.log('DOM unavailable in this runtime');
} else {
const li = (text) => Object.assign(document.createElement('li'), { textContent: text });
const list = document.createElement('ul');
const anchor = li('anchor');
// before/after 插到锚点两侧;append 把它们挂进容器
list.append(li('zero'), anchor);
anchor.before(li('head'));
anchor.after(li('tail'));
// replaceWith 原地换节点;remove 直接摘除,不需要父节点引用
list.firstElementChild.replaceWith(li('replaced'));
list.lastElementChild.remove();
console.log('items:', [...list.children].map((node) => node.textContent).join(','));
}Inside the snippet
One small helper, li, does the tree work here.
Points of care
- Ready as-is in a browser page (or the DevTools console).
- The snippet leans on
document— browser-only surfaces a bare Node process cannot provide.
Putting it to use
Entry signature: const li = (text)
The two runtimes each print one of these labels, never both: Node prints DOM unavailable in this runtime, and a browser prints the items: line.
Core lines
const li = (text) => Object.assign(document.createElement('li'), { textContent: text });
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.Levenshtein Distance CalculatorCompute the classic edit distance between two strings with a space-optimized DP and a normalized similarity percentage.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 before, after And replaceWith Edit Nodes 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.