Why does my `querySelectorAll` result miss elements added later?
Quick answer
querySelectorAll() returns a static NodeList: it records matching elements when the query runs and does not add elements inserted later. Run the query again after adding content if you need an updated collection. If your goal is to handle events on current and future matching descendants, a listener on a stable parent can be a better fit when the event bubbles and propagation is not stopped. [S1] [S2]
The question, the details, the next step.
A practical checklist
Decide whether you need an updated collection or only to handle future events.
For a batch operation, run
querySelectorAll()after the relevant DOM change.For changing descendants, choose a stable parent that contains the controls.
In the delegated handler, identify the intended descendant and scope it to the parent.
If clicks are missed, check event bubbling and whether propagation is stopped.
A few more useful answers
Does calling `querySelectorAll()` again update the old variable?
No. It returns a new result for the query at that time; the earlier NodeList remains a snapshot. Assign the new result if you want to keep using it. [S1]
Will delegation work if a click handler stops propagation?
It may not: stopping propagation can prevent the event from reaching the parent listener. Check the event path and the handlers involved. [S2]
Sources
References used for this guide.
- [S1] Document: querySelectorAll() method — Web APIs | MDN developer.mozilla.org · Checked
- [S2] Event bubbling — Learn web development | MDN developer.mozilla.org · Checked
