prefer-query-selector
Added in v0.10.1Configuration
Rule Details
Prefer .querySelector() and .querySelectorAll() over older DOM query methods.
This rule reports .getElementById(), .getElementsByClassName(),
.getElementsByTagName(), and .getElementsByName() calls to keep DOM queries
consistent. It automatically converts safe literal arguments to CSS selectors.
A following .item(0) becomes a single-element query when it is safe to remove
the access. Indexing with [0] and calls to .at(0) are preserved.
Examples of incorrect code:
Examples of correct code:
Values requiring CSS escaping, dynamic arguments, and empty strings are reported without an automatic fix. Compose and escape dynamic selectors explicitly:
Options
allowWithVariables
Type: boolean
Default: false
When true, allows non-literal arguments to .getElementById() and
.getElementsByClassName(). String literals, binary expressions, and template
literals containing non-whitespace text are still reported. Calls to
.getElementsByTagName() and .getElementsByName() are always checked.
Differences from upstream
The following differences from eslint-plugin-unicorn v79.0.0 keep autofixes from changing query results:
- Generated selectors omit
:scope. For example,fragment.getElementById('foo')becomesfragment.querySelector('#foo'), which also works on shadow roots. - ID, class, and name queries with
nullarguments are reported without a fix. For example,document.getElementById(null)queries the ID'null', whereasdocument.querySelector(null)queries a tag named'null'. - Class names are split only on DOM ASCII whitespace. A query such as
document.getElementsByClassName('foo\u00a0bar')is reported without a fix because the non-breaking space belongs to one class name. - Name queries containing actual form feed or NUL characters are reported without a fix because those characters change meaning inside CSS attribute selectors.
[0]and.at(0)are preserved because they returnundefinedfor an empty collection. Only.item(0)can become.querySelector(), which also returnsnullwhen nothing matches.- Class and tag queries whose result is directly accessed through
.namedItemare reported without a fix becauseNodeListhas no such member. This includes computed access such ascollection['namedItem'].
Collection-returning fixes still produce a static NodeList, as upstream does.
Code that retains a live collection across DOM mutations needs manual review.