JavaScript Syntax Doubt for Case Insensitivity

Hello Everyone! New to this forum and currently learning JS. While working on a Wordle clone, I had a small syntax doubt. In the below command, I am trying to store the element containing the data attribute ( data-key), regardless of the case of the variable letter being received.

const key = keyboard.querySelector(`[data-key="${letter}"i]`)

Is the above syntax correct for making the given command case-insensitive? Or should it be :

const key = keyboard.querySelector(`[data-key="${letter}"/i]`) 

with a forward slash.

welcome to fcc forum :slight_smile:

you know what they say, there is no harm in trying it out for yourself!! it’s just harmless js in browser, what could go wrong, if you try it out?! :grin:

and again, i’d double check on ‘syntax’, try googling about it a bit!! this might be helpful.

happy coding :slight_smile:

1 Like

First, querySelector takes a string as an argument, so you can’t use pattern matching here. Second, the string must be a valid CSS selector string. CSS doesn’t provide a method for doing pattern matching. If you want to select for both lower case and upper case then you will have to use two separate selectors:

keyboard.querySelectorAll("[data-key='a'], [data-key='A']");

UPDATE: Well, I take that back, I didn’t realize CSS now supported case insensitive selectors. My bad.

I would write letter.toLowerCase(), but that’s me not knowing about case-insensitivity of css selectors

1 Like

It is without the slash but you are missing a space.

<p data-key="a">a</p>
<h2 data-key="A">A</h2>
[data-key="a" i] {
  color: red;
}
const letter = 'A'
const key = document.querySelector(`[data-key=${letter} i]`)
const keys = document.querySelectorAll(`[data-key=${letter} i]`)
console.log({key}) // <p>
console.log({keys}) // [p, h2]

https://drafts.csswg.org/selectors-4/#overview

1 Like

(post deleted by author)

Thanks for the help!! :+1:

Thank you so much. Got to know a lot from this!!! :+1: