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 (#7796)

Note: This uses a regex to replace multiple instances of whitespace with
` .`. May not be the most performant, so if there's a simple alternative
I can change to that instead.

cc @camc314, I know this was assigned to you but I just wanted to throw
something quick together while I had a minute. Feel free to use this, or
decline it and write your own.

Fixes #7794.

---------

Co-authored-by: Cameron Clark <[email protected]>
  • Loading branch information
nrayburn-tech and camc314 authored Dec 11, 2024
1 parent bb22c67 commit 06e6d38
Showing 1 changed file with 15 additions and 3 deletions.
18 changes: 15 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 @@ -127,9 +127,21 @@ 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!(
".{}",
literal_value.split_whitespace().collect::<Vec<_>>().join(" .")
)
}
_ => 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 +203,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 06e6d38

Please sign in to comment.