mirror of
https://github.com/danbulant/oxc
synced 2026-05-19 04:08:41 +00:00
fix(linter): Fix unicorn/prefer-query-selector to use the correct replacement 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 <cameron.clark@hey.com>
This commit is contained in:
parent
bb22c67974
commit
06e6d387fa
1 changed files with 15 additions and 3 deletions
|
|
@ -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}"),
|
||||
)
|
||||
});
|
||||
}
|
||||
|
||||
|
|
@ -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),
|
||||
|
|
|
|||
Loading…
Reference in a new issue