Why does JS code "var a = document.querySelector('a[data-a=1]');" cause error? Why does JS code "var a = document.querySelector('a[data-a=1]');" cause error? javascript javascript

Why does JS code "var a = document.querySelector('a[data-a=1]');" cause error?


From the selectors specification:

Attribute values must be CSS identifiers or strings.

Identifiers cannot start with a number. Strings must be quoted.

1 is therefore neither a valid identifier nor a string.

Use "1" (which is a string) instead.

var a = document.querySelector('a[data-a="1"]');


You could use

var a = document.querySelector('a[data-a="1"]');

instead of

var a = document.querySelector('a[data-a=1]');


Because you need parentheses around the value your looking for.So here : document.querySelector('a[data-a="1"]')

If you don't know in advance the value but is looking for it via variable you can use template literals :

Say we have divs with data-price

<div data-price="99">My okay price</div><div data-price="100">My too expensive price</div>

We want to find an element but with the number that someone chose (so we don't know it):

// User chose 99    let chosenNumber = 99document.querySelector(`[data-price="${chosenNumber}"`]