CSS.escape() Sample

Available in Chrome 46+ | View on GitHub | Browse Samples


There are certain strings that are valid when used as an HTML element's id or class attributes, but not valid as a CSS selector string. They include strings that begin with numbers, contain spaces, or contain characters with special meaning in CSS. Mathias Bynens's explanation delves into the full details.

The CSS.escape() method provides a convenient way to escape a string so that it conforms to the CSS selector requirements. This is especially useful when dynamically building a CSS selector based on (untrusted) user input. For example:

A polyfill is available for browsers that do not natively support CSS.escape().

Live Output

Clicking on a button will log the escaped value of its id.

JavaScript Snippet

function logEscapedId(e) {
  ChromeSamples.log('My id is "' + e.target.id + '", and escaped id is "' +
                    CSS.escape(e.target.id) + '"');

var buttons = document.querySelectorAll('button');
for (var i = 0; i < buttons.length; i++) {
  buttons[i].addEventListener('click', logEscapedId);