CSS Escape Selector Values
CSS.escape renders arbitrary ids and user-derived strings safe inside querySelector, where an unescaped colon or dot throws SyntaxError.
Code
// 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
CSS Specificity CalculatorCalculate CSS selector specificity scores using the standard (a, b, c) notation. Enter any selector and see its inline, ID, class, and element contributions instantly.Regex Escape GeneratorEscape plain text so it can be embedded safely in a JavaScript RegExp, covering all metacharacters like dots, brackets, braces, and backslashes.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.