CSS.escape Polyfill

1.5.1 · maintenance · verified Sun Apr 19

This package provides a robust polyfill for the `CSS.escape` utility method, as defined in the CSSOM specification. It ensures that CSS identifiers can be safely escaped, preventing syntax errors when dealing with strings that might contain special CSS characters (e.g., spaces, hashes, dots). Currently at version 1.5.1, the package appears to be in a maintenance state with its last update several years ago, as the `CSS.escape` method is now widely supported natively in modern browsers. For applications requiring more advanced escaping options, such as handling excessive whitespace or custom output formats, the `cssesc` package is recommended as a more powerful alternative.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to include the `css.escape` polyfill in a Node.js environment using CommonJS `require` and then utilize the globally available `CSS.escape` method to safely escape strings for use in CSS selectors or identifiers.

require('css.escape');

// Verify that CSS.escape is available
if (typeof CSS !== 'undefined' && typeof CSS.escape === 'function') {
  const escapedId = CSS.escape('.my-class#with spaces!');
  console.log(`Original: .my-class#with spaces!`);
  console.log(`Escaped: ${escapedId}`); // Expected: \.my-class\#with\ spaces\!

  const escapedSelector = `#${CSS.escape('user id')}`;
  console.log(`Selector for 'user id': ${escapedSelector}`); // Expected: #user\ id

  const trickyString = '123_abc-def';
  console.log(`Escaped: ${CSS.escape(trickyString)}`); // Expected: 123_abc-def (no change needed)
} else {
  console.error('CSS.escape is not available after polyfill attempt.');
}

view raw JSON →