JS Quiz: Hard: Node list snapshot vs live collection

Assuming this runs in a browser, what logs?

const ul = document.createElement('ul');
ul.innerHTML = '<li>A</li><li>B</li>';
document.body.appendChild(ul);

const staticList = ul.querySelectorAll('li');
const liveList = ul.getElementsByTagName('li');

const li = document.createElement('li');
li.textContent = 'C';
ul.appendChild(li);

console.log(staticList.length, liveList.length);
  • 2 2
  • 3 3
  • 2 3
  • 3 2
0 voters

It logs 2 3.

querySelectorAll('li') is a snapshot-y NodeList, so it stays stuck at 2 even after you append C. getElementsByTagName('li') hands you a live HTMLCollection, so it updates under your feet and reports 3 (which is why looping it while mutating the DOM can get real weird).

JS Quiz answer: Option 3 (C).

Correct choice: 2 3

Why:
querySelectorAll gives a static snapshot, while getElementsByTagName is live.

Go deeper:

https://www.kirupa.com/html5/ai/advanced_random_numbers_js.md

Sarah :grinning_face: