Explain Codes LogoExplain Codes Logo

Why does JS code "var a = document.querySelector('a

javascript
prompt-engineering
best-practices
responsive-design
Nikita BarsukovbyNikita BarsukovΒ·Jan 8, 2025
⚑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:

var a = document.querySelector('a[data-a="1"]'); // 🎡'Those quotes saved you,' said JavaScript.😁

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:

// String value selector: Elvis has entered the building πŸ‘‘ var divDataVal = document.querySelector('div[data-val="123"]'); // Dynamic value selector: Here comes the variable train! Choo choo! πŸš‚ let myValue = 'dynamicValue'; var divDynamic = document.querySelector(`div[data-dynamic="${CSS.escape(myValue)}"]`);

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! ✏️