Skip to content

Latest commit

Β 

History

History
42 lines (27 loc) Β· 1.74 KB

File metadata and controls

42 lines (27 loc) Β· 1.74 KB

prefer-scoped-selector

πŸ“ Prefer :scope when using element query selector methods.

πŸ’ΌπŸš« This rule is enabled in the βœ… recommended config. This rule is disabled in the β˜‘οΈ unopinionated config.

πŸ’‘ This rule is manually fixable by editor suggestions.

When calling querySelector() or querySelectorAll() on an element, use :scope to make selector matching explicit.

Without :scope, browser selector matching can consider ancestors outside the element and only filter the final matched element to the element subtree.

This only matters for selectors with a combinator (descendant .outer .inner, child >, or sibling +/~). A simple selector like .a, or a list of simple selectors like .a, b, is left alone because :scope would only add noise.

Examples

// ❌
element.querySelectorAll('.outer .inner');

// βœ…
element.querySelectorAll(':scope .outer .inner');
// βœ…
element.querySelector('.a, b');
// βœ…
document.querySelectorAll('.outer .inner');

Limitations

The rule only checks selectors written as a string literal or a template literal without expressions. Dynamic selectors are ignored.

It does not look inside functional pseudo-classes like :is(), :where(), :not(), and :has(), so a branch counts as scoped as long as it contains :scope somewhere. For example, :scope div:is(.a, div b) is accepted even though div b is not scoped.