Skip to content

Latest commit

Β 

History

History
82 lines (58 loc) Β· 2.01 KB

File metadata and controls

82 lines (58 loc) Β· 2.01 KB

no-incorrect-query-selector

πŸ“ 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.

Examples

// ❌
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;

Limitations

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.