eslint-plugin-unicorn icon indicating copy to clipboard operation
eslint-plugin-unicorn copied to clipboard

Add option to allow variable IDs and classes in `prefer-query-selector`

Open fregante opened this issue 2 years ago • 3 comments

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)

fregante avatar Jan 26 '22 09:01 fregante

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
	}]
}

fregante avatar Mar 28 '22 04:03 fregante

I'm fine with an option as long as it's false by default.

sindresorhus avatar Jun 05 '22 09:06 sindresorhus

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.

silverwind avatar Mar 31 '24 02:03 silverwind