Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(linter): Fix unicorn/prefer-query-selector to use the correct replacement for getElementsByClassName #7796

Merged
merged 2 commits into from
Dec 11, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading