实现说明
list、item、inserted 定义在模块顶层,中间不经过函数作用域。
使用要点
document只存在于浏览器——Node 运行时没有现成的垫片。- 跑完文件,输出里会留下标记——
returned node:、append returns:、child count:。
常见问题
「append 收多个,appendChild 还一个」能在裸 Node.js 里跑吗?
不能——它用到 document。这些 API 只在浏览器里有效,裸 Node 进程没有这些能力,请放到页面(或 DevTools 控制台)里执行。
核心语句
list.append('plain text', document.createElement('li'));
list.replaceChildren(document.createElement('li'));
const list = document.querySelector('#list');
代码示例
const list = document.querySelector('#list');
// appendChild takes exactly one node and returns the inserted node
const item = document.createElement('li');
item.textContent = 'first';
const inserted = list.appendChild(item);
console.log('returned node:', inserted === item);
// append accepts multiple arguments and plain strings (inserted as text nodes)
list.append('plain text', document.createElement('li'));
// append returns nothing: use appendChild when you need the node reference
console.log('append returns:', list.append('x'));
// clearing and rebuilding in one call belongs to replaceChildren
list.replaceChildren(document.createElement('li'));
console.log('child count:', list.childElementCount);