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.

JavascriptData Integrity

Code

javascriptsnippet
18 lines
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

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.