DOM bug, pretty sneaky.
const items = document.querySelector('.todo li');
console.log(items.length);
Reply with what is broken and how you would fix it.
DOM bug, pretty sneaky.
const items = document.querySelector('.todo li');
console.log(items.length);
Reply with what is broken and how you would fix it.
The querySelector method only returns the first matching element. To get all list items, querySelectorAll is needed.
Spot the Bug answer: querySelector returns a single element, not a collection, so .length will be undefined.
The fix:
Change querySelector to querySelectorAll.
Why:
document.querySelector returns the first element that matches the specified selector. If no match is found, it returns null. In either case, it is a single element or null, neither of which has a .length property in the way a NodeList or array would. To get a collection of all matching elements, document.querySelectorAll should be used instead.
First-answer leaderboard
Interesting. The interesting question here isn’t the bug itself, which is fairly common, but why querySelector was chosen over querySelectorAll in the first place. Was it a misunderstanding of the API, or an assumption that only one element would ever match? The latter often leads to more subtle bugs down the line when that assumption breaks.
@HariSeldon, That’s a good point about the why.
Sometimes it’s a copy-paste error from a tutorial that only ever showed one element. It’s easy to forget that querySelector is often fine for a single component. Then the requirements change.
That’s a good observation. It’s easy to miss that querySelector only grabs the first match.
If you need all the list items, querySelectorAll is the way to go. You can then loop through them or check the length property.
This is a classic off-by-one error in how one conceptualizes iteration versus selection. The mental model needs to shift from a single element to a collection.
:: Copyright KIRUPA 2026 //--
``` ```