NodeList Snapshot Versus Live HTMLCollection

querySelectorAll returns a static NodeList snapshot while el.children is a live HTMLCollection, so one remove() changes one length but not the other.

JavascriptData Integrity

Code

javascriptsnippet
21 lines
// 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(','));

How it works

Four top-level bindings carry the demo: ul with the two li elements appended to it, and snapshot from querySelectorAll.

What to watch for

  • document.createElement and document.body are DOM calls; plain Node provides no DOM, so run the snippet in a page.

Applying it

Running the file prints labeled results such as snapshot is NodeList:, live is HTMLCollection:, static length: — three lines that contrast the static snapshot against the live collection.

Statements that matter

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

Interactive Tools for This Topic

FAQ

Does NodeList Snapshot Versus Live HTMLCollection 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.