oxc-project/oxc · error · OxcDiagnostic
Prefer `.{good_method}()` over `.{bad_method}()`.
Error message
Prefer `.{good_method}()` over `.{bad_method}()`. What it means
Emitted by the unicorn/prefer-query-selector rule when it finds a DOM query call using `getElementById`, `getElementsByClassName`, `getElementsByTagName`, or `getElementsBy*Name`-style methods. It fires at the call-expression span because those legacy DOM query methods are less flexible and less consistent than the modern `querySelector`/`querySelectorAll` API, which supports full CSS selectors.
Source
Thrown at crates/oxc_linter/src/rules/unicorn/prefer_query_selector.rs:13
use oxc_ast::{AstKind, ast::Expression};
use oxc_diagnostics::OxcDiagnostic;
use oxc_macros::declare_oxc_lint;
use oxc_span::{GetSpan, Span};
use crate::{AstNode, context::LintContext, rule::Rule, utils::is_node_value_not_dom_node};
fn prefer_query_selector_diagnostic(
good_method: &str,
bad_method: &str,
span: Span,
) -> OxcDiagnostic {
OxcDiagnostic::warn(format!("Prefer `.{good_method}()` over `.{bad_method}()`."))
.with_help("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).")
.with_label(span)
}
#[derive(Debug, Default, Clone)]
pub struct PreferQuerySelector;
fn get_preferred_identifier_name(ident_name: &str) -> Option<&'static str> {
match ident_name {
"getElementById" => Some("querySelector"),
"getElementsByClassName" | "getElementsByTagName" | "getElementsByName" => {
Some("querySelectorAll")
}
_ => None,
}
}
declare_oxc_lint!(View on GitHub (pinned to e1e7af627c)
Solutions
- Replace `document.getElementById('id')` with `document.querySelector('#id')`
- Replace `document.getElementsByClassName('c')` with `document.querySelectorAll('.c')`
- Replace `document.getElementsByTagName('div')` with `document.querySelectorAll('div')`
Defensive patterns
Strategy: validation
When it happens
Trigger: Thrown at crates/oxc_linter/src/rules/unicorn/prefer_query_selector.rs:13 when the library encounters an invalid state.
Common situations: See trigger scenarios.
AI-assisted analysis of oxc-project/oxc@e1e7af627c (2026-08-20).
Data as JSON: /api/errors/23d560d5141b0868.
Report an issue: GitHub.