← 中文资源

简体中文版本

querySelectorAll 快照对比 children 动态集合

querySelectorAll 返回静态 NodeList 快照,el.children 返回动态 HTMLCollection:同一个 remove() 之后两者 length 不同;NodeList 自带 forEach,HTMLCollection 要先展开成数组。

阅读英文原文

实现说明

ul、one、two、snapshot 定义在模块顶层,中间不经过函数作用域。

使用要点

  • 用到了 document,需要在浏览器环境运行,Node 里直接跑会缺 API。
  • 演示输出是带标签的(snapshot is NodeList:、live is HTMLCollection:、static length:),每个操作都会留下自己的一行标注。

常见问题

「querySelectorAll 快照对比 children 动态集合」能在裸 Node.js 里跑吗?

不能——这类 API 归浏览器环境所有(document),Node 里不存在。请在页面或 DevTools 控制台中运行。

核心语句

const snapshot = document.querySelectorAll('li');
const one = document.createElement('li');
const two = document.createElement('li');

代码示例

// querySelectorAll 返回静态(static)NodeList 快照;el.children 返回动态(live)HTMLCollection
const ul = document.createElement('ul');
const one = document.createElement('li');
const two = document.createElement('li');
one.textContent = 'one';
two.textContent = 'two';
ul.append(one, two);
document.body.append(ul);

const snapshot = document.querySelectorAll('li');
const live = ul.children;
console.log('snapshot is NodeList:', snapshot instanceof NodeList);
console.log('live is HTMLCollection:', live instanceof HTMLCollection);

two.remove();
// 静态快照保持删除之前的长度;动态集合立即反映 DOM 变化
console.log('static length:', snapshot.length, '| live length:', live.length);

// NodeList 自带 forEach;HTMLCollection 没有,先展开成数组再 map
snapshot.forEach((li) => console.log('static item:', li.textContent));
console.log('live via spread:', [...live].map((li) => li.textContent).join(','));