unicorn/prefer-query-selector Pedantic
What it does
Prefer .querySelector() over .getElementById(). And prefer .querySelectorAll() over .getElementsByClassName(), .getElementsByTagName(), and .getElementsByName().
Why is this bad?
- Using
.querySelector()and.querySelectorAll()is more flexible and allows for more specific selectors. - It's better to use the same method to query DOM elements. This helps keep consistency and it lends itself to future improvements (e.g. more specific selectors).
Examples
Examples of incorrect code for this rule:
javascript
document.getElementById("foo");
document.getElementsByClassName("foo bar");
document.getElementsByTagName("main");
document.getElementsByClassName(fn());
document.getElementsByName("foo");Examples of correct code for this rule:
javascript
document.querySelector("#foo");
document.querySelector(".bar");
document.querySelector("main #foo .bar");
document.querySelectorAll(".foo.bar");
document.querySelectorAll("li a");
document.querySelector("li").querySelectorAll("a");Examples of correct code for this rule with { "allowWithVariables": true }:
javascript
document.getElementById(someId);
document.getElementsByClassName(someClass);
document.getElementsByClassName(`${someClass}`);Configuration
This rule accepts a configuration object with the following properties:
allowWithVariables
type: boolean
default: false
When set to true, allows using .getElementById() and .getElementsByClassName() when called with a variable or expression. This avoids the need to manually compose a CSS selector string, which can be less readable.
How to use
To enable this rule using the config file or in the CLI, you can use:
json
{
"rules": {
"unicorn/prefer-query-selector": "error"
}
}ts
import { defineConfig } from "oxlint";
export default defineConfig({
rules: {
"unicorn/prefer-query-selector": "error",
},
});bash
oxlint --deny unicorn/prefer-query-selectorVersion
This rule was added in v0.0.15.
