CSS Escape Selector Values

CSS.escape renders arbitrary ids and user-derived strings safe inside querySelector, where an unescaped colon or dot throws SyntaxError.

JavascriptSecurity Boundaries

Code

snippet
// CSS.escape makes arbitrary strings safe inside selectors — ids, classes,
// or user-derived values may contain colons, dots, or leading digits
const userId = 'user:42';
const target = document.createElement('div');
target.id = userId;
target.dataset.role = 'admin';
document.body.append(target);

// unescaped: ':42' parses as a pseudo-class and throws
try {
  document.querySelector('#' + userId);
} catch (err) {
  console.log('raw selector throws:', err.constructor.name);
}

const safe = '#' + CSS.escape(userId);
console.log('escaped selector:', safe);
const row = document.querySelector(safe);
console.log('found role:', row && row.dataset.role);

// ids cannot start with a digit; CSS.escape knows the escape form
console.log('escaped digits:', CSS.escape('9lives'));
console.log('escaped dots:', CSS.escape('cfg.db.host'));

Tracing the logic

Top-level bindings userId, target, safe, row hold the demo state — nothing sits inside a function scope.

What to watch for

  • Zero-fetch snippet: every identifier resolves inside the language distribution.
  • The snippet leans on document — browser-only surfaces a bare Node process cannot provide.

Using it

Lines print with labels — raw selector throws:, escaped selector:, found role: — when the file runs.

Key statements

const target = document.createElement('div');
const row = document.querySelector(safe);
const safe = '#' + CSS.escape(userId);

Interactive Tools for This Topic

FAQ

Does CSS Escape Selector Values run in plain Node.js?
No — it touches `document`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.