Why the es6 template-string needs double quart in this occasion Javascript?

61 Views Asked by At

I`m on the Javascript30 #1 now, and I`ve been wondering about a small stuff...

This code below worked.

const audio = document.querySelector(`audio[data-key="${e.keyCode}"]`);

But, this code below threw an error.

const audio = document.querySelector(`audio[data-key=${e.keyCode}]`);

Why do these happen?
As far as I checked, any variable and strings are valid if it`s surrounded by back-quarts and using ${} though...

2

There are 2 best solutions below

0
On BEST ANSWER

The issue is not with the template string, it is about the selector value passed in the querySelector.

data-* values are strings. Number values also must be quoted to use them in the selector.

In your first code the values are string and passes the test where as in the second code (not wrapped with quotes) they are not treated as valid selector.

1
On

Look at the output...

`audio[data-key="${e.keyCode}"]`
"audio[data-key="Y"]"

`audio[data-key=${e.keyCode}]`
"audio[data-key=Y]"

The former won't work as a selector due to the missing quotes ("Y" or 'Y').

However, I've double-checked and it looks like Chrome works. Take this page... the following work

var q = "q"
document.querySelector(`#search > div > input[name="${q}"]`)
document.querySelector(`#search > div > input[name='${q}']`)
document.querySelector(`#search > div > input[name=${q}]`)

NOT AN ANSWER SORRY :)