Why does JS code "var a = document.querySelector('a
β‘TLDR
The code fails since the JavaScript engine misinterprets the equals sign (=
) in the attribute selector.
The correct way is to wrap the data-a=1
value in quotes:
Quoting attribute values in selectors is necessary to prevent parsing issues and to ensure the selector is interpreted correctly.
Following the W3C Selectors Specification, attribute values in selectors need to be represented as CSS strings or identifiers.
Deep Dive: How Does querySelector
Work?
Attribute selectors: Just put 'em in quotes!
Following CSS identifier or string rules, attribute values in the querySelector
should be:
- Enclosed in quotes, either single (
'
) or double quotes ("
), even when they're numeric. - Processed as CSS identifiers or strings. Non-string values without quotes throw an error.
Quoting consistency and browser support
To avoid selector errors:
- Keep the quoting consistent throughout your code.
- Stay up-to-date with your browser's
querySelector
support.
HTML5 Spec influence
The HTML5 specification influences querySelector
by stating:
- Attribute values in the DOM must be strings.
- Consequently, numeric values must always be enclosed in quotes when used as a CSS selector.
Safety measures
When constructing selectors:
- Use template literals to include variables without the fear of syntax errors.
- Make use of
CSS.escape()
to prevent breaking the query with special characters.
querySelector
in Action
Spot-on HTML5 and quoting
To avoid syntax issues:
- Be sure to validate your HTML5.
- Maintain consistent quoting around attribute values in selectors.
Real-life examples
Consider these practical scenarios:
Turning Errors into Opportunities
- Unmatched quotes could lead to syntax errors: When in doubt, quote it out!
- Using non-string values without quotes in a selector: Just because you can doesnβt mean you should! π·ββοΈ
- Using parentheses instead of quotes: These aren't for the taking; return them to math! βοΈ
ξ’Linked
Was this article helpful?