From 06e6d387fa7749531f826efa028cc2a37f32ff96 Mon Sep 17 00:00:00 2001 From: Nicholas Rayburn <52075362+nrayburn-tech@users.noreply.github.com> Date: Wed, 11 Dec 2024 02:49:40 -0600 Subject: [PATCH] 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 --- .../src/rules/unicorn/prefer_query_selector.rs | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/crates/oxc_linter/src/rules/unicorn/prefer_query_selector.rs b/crates/oxc_linter/src/rules/unicorn/prefer_query_selector.rs index 4026bfc6e..a4e356bfc 100644 --- a/crates/oxc_linter/src/rules/unicorn/prefer_query_selector.rs +++ b/crates/oxc_linter/src/rules/unicorn/prefer_query_selector.rs @@ -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::>().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),