CSS: escape() 静的メソッド

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.

CSS.escape() は静的メソッドで、 CSS セレクターの一部として使用するために引数として渡されるエスケープ処理された文字列の入った文字列を返します。

構文

js
CSS.escape(str)

引数

str

エスケープ処理する文字列です。

返値

エスケープされた文字列です。

基本的な結果

js
CSS.escape(".foo#bar"); // "\.foo\#bar"
CSS.escape("()[]{}"); // "\(\)\[\]\{\}"
CSS.escape('--a'); // "--a"
CSS.escape(0); // "\30 " ('0' の Unicode コードポイントは 30)
CSS.escape('\0'); // "\ufffd" (Unicode REPLACEMENT CHARACTER)

コンテキスト内での使用

セレクターの一部として使用するために文字列をエスケープするには、 escape() メソッドを使用します。

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

escape() メソッドは文字列のエスケープにも使えますが、厳密にはエスケープする必要がない文字もエスケープしてしまいます。

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

仕様書

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

ブラウザーの互換性

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

関連情報