CSS: escape() static method

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since January 2020.

The CSS.escape() static method returns a string containing the escaped string passed as parameter, mostly for use as part of a CSS selector.

Syntax

js
CSS.escape(str)

Parameters

str

The string to be escaped.

Return value

The escaped string.

Examples

Basic results

js
CSS.escape(".foo#bar"); // "\\.foo\\#bar"
CSS.escape("()[]{}"); // "\\(\\)\\[\\]\\{\\}"
CSS.escape('--a'); // "--a"
CSS.escape(0); // "\\30 ", the Unicode code point of '0' is 30
CSS.escape('\0'); // "\ufffd", the Unicode REPLACEMENT CHARACTER

In context uses

To escape a string for use as part of a selector, the escape() method can be used:

js
const element = document.querySelector(`#${CSS.escape(id)} > img`);

The escape() method can also be used for escaping strings, although it escapes characters that don't strictly need to be escaped:

js
const element = document.querySelector(`a[href="#${CSS.escape(fragment)}"]`);

Specifications

Specification
CSS Object Model (CSSOM)
# the-css.escape()-method

Browser compatibility

BCD tables only load in the browser

See also