eslint-plugin-unicorn
eslint-plugin-unicorn copied to clipboard
Add option to allow variable IDs and classes in `prefer-query-selector`
Occasionally it's easier to deal with IDs:
const field = labelElement.htmlFor;
return <input id={field}>;
const element = document.getElementById(field)
It's kind of an exception, but this doesn't feel like an improvement in any metric:
- const element = document.getElementById(field)
+ const element = document.querySelector('#' + field)
I had opened a duplicate issue with more examples, 😅 I'll copy it down here:
querySelector
and querySelectorAll
are great APIs, but are not necessarily "better" than the existing ones.
Both of these are fine, even though I'd also prefer qSA here:
document.getElementsByClassname('class') ✅
document.querySelectorAll('.class') ✅
However here qSA is making the code unnecessarily complex/noisy, to the point that qSA isn't any shorter either:
document.getElementsByClassname(someClass) ✅
document.querySelectorAll('.' + someClass) 🥴
document.querySelectorAll(`.${someClass}`) 🥴
the same applies to getElementById
, where this rule even lengthens the code:
document.getElementById(someId) ✅
document.querySelector('#' + someId) 🤢
document.querySelector(`#${someId}`) 🤢
Can we have an option to allow the """old""" APIs when they're used with existing variables?
{
"unicorn/prefer-query-selector": ["error", {
"allowWithVariables": true
}]
}
I'm fine with an option as long as it's false by default.
querySelector and querySelectorAll are great APIs, but are not necessarily "better" than the existing ones.
Agree. For cases like single class, querySelectorAll
is magnitudes slower then getElementsByClassname
for example. In one benchmark I've seen it was 500 times slower in a DOM with 5000 elements.
I'd definitely welcome a new rule or set of options that recommends getElementsByClassname
, getElementById
etc for performance reasons.