CSS: escape() statische Methode

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.

Die CSS.escape() statische Methode gibt einen String zurück, der den übergebenen, escaped String enthält, hauptsächlich zur Verwendung als Teil eines CSS-Selektors.

Syntax

js
CSS.escape(str)

Parameter

str

Der zu escapende String.

Rückgabewert

Der escapte String.

Beispiele

Grundlegende Ergebnisse

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

Verwendung im Kontext

Um einen String für die Verwendung als Teil eines Selektors zu escapen, kann die escape() Methode verwendet werden:

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

Die escape() Methode kann auch für das Escapen von Strings verwendet werden, obwohl sie Zeichen escaped, die nicht zwingend escapet werden müssten:

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

Spezifikationen

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

Browser-Kompatibilität

Report problems with this compatibility data on GitHub
desktopmobile
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
escape() static method

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support

Siehe auch