How can I select one specific element without accidentally matching several?
Quick answer
Use getElementById() when you know the element’s unique ID; use querySelector() when a CSS selector should identify the first match; and use querySelectorAll() when you intend to handle every match. Before updating a single element, check that the result is not null. For a collection, check its length. If you expect one match, check the count rather than assuming the selector found only one.
The question, the details, the next step.
A practical checklist
Use
getElementById()for a known ID that is intended to be unique.Use
querySelector()for one CSS-selected match, remembering it returns the first even if several match.Use
querySelectorAll()when the task is to handle every match.Check a single result before accessing or updating it; check a collection’s
length.If exactly one match is expected, decide how to handle zero or multiple matches.
A few more useful answers
Does `querySelector()` tell me whether my selector matches exactly one element?
What does `querySelectorAll()` return when nothing matches?
It returns an empty NodeList, so check whether its length is zero before processing it. [S3]
Can `getElementById()` catch duplicate IDs?
No. IDs are intended to be unique, but if duplicates exist, getElementById() returns the first matching element. [S1]
Sources
References used for this guide.
- [S1] Document: getElementById() method — Web APIs | MDN developer.mozilla.org · Checked
- [S2] Element: querySelector() method — Web APIs | MDN developer.mozilla.org · Checked
- [S3] Document: querySelectorAll() method — Web APIs | MDN developer.mozilla.org · Checked
