← 中文资源

简体中文版本

before/after/replaceWith 就地编辑节点

before/after 把节点插到锚点两侧,replaceWith 原地替换、remove 直接摘除——都不需要父节点引用,比 insertBefore 直观得多。

阅读英文原文

实现说明

before/after/replaceWith 就地编辑节点可以归结为函数 li。

使用要点

  • 用到了 document,需要在浏览器环境运行,Node 里直接跑会缺 API。
  • 跑完文件,输出里会留下标记——DOM unavailable in this runtime、items:。

常见问题

「before/after/replaceWith 就地编辑节点」能在裸 Node.js 里跑吗?

不能——document 的家在浏览器里,Node 进程提供不了。执行时请用页面(或 DevTools 控制台)。

主要签名是 const li = (text)

核心语句

const li = (text) => Object.assign(document.createElement('li'), { textContent: text });

代码示例

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(','));
}