jQuery.escapeSelector(selector) (alias $.escapeSelector) escapes characters that have special meaning in CSS so you can use them as literal class or ID text (since jQuery 3.0).
Syntax
Start with these common calls. Keep them short and readable.
jQuery
$.escapeSelector("#target") // "\#target"
"." + $.escapeSelector(".box") // ".\.box"
// Still prepend . or # yourself — escape only the name.
Call
What it does
selector
String to escape (identifier fragment)
Return value
Escaped string safe inside a CSS selector
Load jQuery before your script (CDN or local file), then wrap DOM work in $(function () { ... }) when needed.
Parameters
Parameter
Description
Step 1
Start with a class or ID string that may contain CSS punctuation.
Step 2
Call $.escapeSelector(name) to escape special characters.
Step 3
Prepend "." or "#" to form a complete selector.
Return Value
Return Value
Description
jQuery object
Most setters and traversing helpers return the jQuery collection so you can chain more methods.
Value / undefined
Getters usually return a value from the first matched element, or undefined when nothing applies.
jQuery Examples
Example 1 — Escape an ID Containing #
Official style: escape a string that starts with a hash.
Weird ID. The element’s id attribute is literally #target.
Escape first. Escape the ID string, then prepend another #.
Query.$(sel) matches that one element.
Frequently Asked Questions
jQuery.escapeSelector(selector) returns a string where CSS-special characters are escaped so they act as literal text inside a selector. Use it on the identifier part of a class or ID — then still prepend . or # yourself.
It was added in jQuery 3.0 as a static utility: $.escapeSelector(str). It is not deprecated and remains the idiomatic way to build safe dynamic selectors in jQuery apps.
Both escape identifier characters for CSS. CSS.escape() is a native browser API. $.escapeSelector() is a jQuery shim so the same escape works in all browsers jQuery supports. Prefer $.escapeSelector() inside jQuery code.
Yes. escapeSelector only escapes the name. Build class selectors with "." + $.escapeSelector(name) and ID selectors with "#" + $.escapeSelector(id).
No. Call jQuery.escapeSelector(str) or $.escapeSelector(str). It returns a string — it is not chained on a jQuery collection.
Whenever a class or ID may contain #, ., :, [, ], spaces, or other CSS punctuation — CMS names, user-generated tokens, or literal names like .box and #target.