Skip to content

Commit

Permalink
fix(linter): Fix unicorn/prefer-query-selector to use the correct rep…
Browse files Browse the repository at this point in the history
…lacement for getElementsByClassName
  • Loading branch information
nrayburn-tech committed Dec 11, 2024
1 parent 4a524ed commit b8877df
Showing 1 changed file with 14 additions and 3 deletions.
17 changes: 14 additions & 3 deletions crates/oxc_linter/src/rules/unicorn/prefer_query_selector.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use oxc_diagnostics::OxcDiagnostic;
use oxc_macros::declare_oxc_lint;
use oxc_span::{GetSpan, Span};
use phf::phf_map;
use regex::Regex;

use crate::{context::LintContext, rule::Rule, utils::is_node_value_not_dom_node, AstNode};

Expand Down Expand Up @@ -127,9 +128,19 @@ impl Rule for PreferQuerySelector {
// argument_expr.span().source_text(ctx.source_text());
let source_text = fixer.source_range(argument_expr.span());
let quotes_symbol = source_text.chars().next().unwrap();
let sharp = if cur_property_name.eq(&"getElementById") { "#" } else { "" };
let argument = match *cur_property_name {
"getElementById" => format!("#{literal_value}"),
"getElementsByClassName" => format!(
".{}",
Regex::new(r"\s+").unwrap().replace_all(literal_value, " .")
),
_ => literal_value.to_string(),
};
let span = property_span.merge(&argument_expr.span());
fixer.replace(span, format!("{preferred_selector}({quotes_symbol}{sharp}{literal_value}{quotes_symbol}"))
fixer.replace(
span,
format!("{preferred_selector}({quotes_symbol}{argument}{quotes_symbol}"),
)
});
}

Expand Down Expand Up @@ -191,7 +202,7 @@ fn test() {
("document.getElementsByTagName('foo');", "document.querySelectorAll('foo');", None),
(
"document.getElementsByClassName(`foo bar`);",
"document.querySelectorAll(`foo bar`);",
"document.querySelectorAll(`.foo .bar`);",
None,
),
("document.getElementsByClassName(null);", "document.querySelectorAll(null);", None),
Expand Down

0 comments on commit b8877df

Please sign in to comment.