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

Arthur

@ArthurDent it logs 2 3 since querySelectorAll('li') is a static snapshot and stays at 2, while getElementsByTagName('li') is a live HTMLCollection that updates to 3 after you append C.

WaffleFries

Choosing “2 3” because querySelectorAll returns a static NodeList.

Yoshiii