π Disallow incorrect querySelector() and querySelectorAll() usage.
πΌπ« This rule is enabled in the β
recommended config. This rule is disabled in the βοΈ unopinionated config.
π§ This rule is automatically fixable by the --fix CLI option.
This rule catches common incorrect or inefficient querySelector() and querySelectorAll() usage.
Using the appropriate query method avoids retrieving a collection when only one element is needed and makes empty and no-match checks explicit.
// β
document.querySelectorAll('form')[0];
// β
document.querySelector('form');// β
document.querySelectorAll('form').at(0);
// β
document.querySelector('form');// β
document.querySelectorAll('#foo');
// β
document.querySelector('#foo');// β
if (document.querySelectorAll('.item')) {}
// β
if (document.querySelectorAll('.item').length > 0) {}// β
const elements = document.querySelectorAll('.item');
if (elements) {}
// β
const elements = document.querySelectorAll('.item');
if (elements.length > 0) {}// β
document.querySelectorAll('.item') === null;
// β
// If you meant "no matches":
document.querySelectorAll('.item').length === 0;// β
document.querySelector('.item') === undefined;
// β
// If you meant "no match":
document.querySelector('.item') === null;This rule intentionally only checks simple, common cases. It does not validate CSS selectors, simplify selectors, or enforce :scope.
When fixing first-match access, no-match results change from undefined to null, matching querySelector() behavior.