The jQuery.escapeSelector() utility escapes CSS special characters in a string so you can safely splice it into jQuery selector expressions. This tutorial covers syntax, the official jQuery API example, selecting elements with literal dots or hashes in class and id names, comparisons with CSS.escape() and attribute selectors, and building dynamic selectors from user input.
01
Syntax
$.escapeSelector(str)
02
Static API
On jQuery / $
03
Since 3.0
jQuery 3.0+
04
Returns string
Escaped identifier
05
Literal names
Dots & hashes in ids
06
Dynamic builds
Safe user input
Fundamentals
Introduction
CSS selectors treat certain characters as syntax. A dot means “class,” a hash means “id,” brackets introduce attribute filters, and colons start pseudo-classes. That works perfectly until an element’s actual class or id attribute value contains one of those characters — for example class=".box" or id="#list".
jQuery added jQuery.escapeSelector() (also written $.escapeSelector()) in version 3.0 so developers can escape identifier strings before concatenating them into selectors like "." + escaped or "#" + escaped. Without escaping, $(".box") finds elements with class box, not the rare but real case where the class name is literally .box.
Concept
Understanding the jQuery.escapeSelector() Method
jQuery.escapeSelector(selector) accepts one string argument and returns a new string with backslash escapes inserted wherever CSS would otherwise interpret a character as selector syntax. The result is meant to be embedded inside a larger selector — you still add the leading . for classes or # for ids yourself.
This is a static utility on the jQuery namespace, not a method you call on a collection. It does not query the DOM; it only prepares text. Common special characters that get escaped include #, ., [, ], :, spaces, and other punctuation that Sizzle would parse as operators.
💡
Beginner Tip
Think of escapeSelector as quoting the “name” part of a selector. $.escapeSelector("#target") returns \#target — then "#" + $.escapeSelector("#target") becomes a valid id selector for an element whose id is literally #target.
Foundation
📝 Syntax
General form of jQuery.escapeSelector:
jQuery
jQuery.escapeSelector( selector )
// or
$.escapeSelector( selector )
Parameters
selector — a string representing part of a CSS identifier (a class name, id value, or similar fragment) that may contain special characters.
Return value
A string with special CSS characters escaped so it can be safely concatenated into a jQuery selector.
The original string is not modified; a new escaped copy is returned.
Official jQuery API example
jQuery
$.escapeSelector( "#target" );
// "\#target"
Cheat Sheet
⚡ Quick Reference
Goal
Code
Escape an identifier string
$.escapeSelector(str)
Class selector from variable
$("." + $.escapeSelector(name))
Id selector from variable
$("#" + $.escapeSelector(id))
Collection method?
No — static on jQuery
Minimum jQuery version
3.0+
Native alternative
CSS.escape() (identifiers only)
Compare
📋 $.escapeSelector vs CSS.escape vs manual vs attributes
Four ways to handle tricky class and id values — pick the right tool for jQuery selector building.
$.escapeSelector
"." + $.escapeSelector(n)
jQuery 3.0+; Sizzle-ready fragments
CSS.escape
CSS.escape(name)
Native ES2015; single identifiers
Manual
name.replace(/([#.])/g,"\\$1")
Error-prone; easy to miss chars
Attribute
[class=" .box "]
Exact match; quote carefully
Hands-On
Examples Gallery
Each example uses $.escapeSelector(). Open DevTools or use the Try-it links. Example 1 matches the official jQuery API documentation.
📚 Getting Started
Escape special characters before splicing strings into selectors.
Example 1 — Official jQuery API Demo: Escape #target
Return an escaped string for an id value that contains a hash — the exact example from the jQuery documentation.
jQuery
var escaped = $.escapeSelector("#target");
console.log(escaped);
// "\#target"
// Use when the element's id attribute is literally "#target":
// $("#" + $.escapeSelector("#target"))
Without escaping, a raw # inside a selector starts an id lookup. $.escapeSelector prefixes the hash with a backslash so Sizzle treats it as a literal character in the identifier.
📈 Practical Patterns
Literal class names, id edge cases, and user-driven selector building.
Example 2 — Select Elements Whose Class Is Literally .box
Highlight only the div whose class attribute value is .box, not ordinary box elements.
jQuery
// HTML includes:
// <div class="box">Normal</div>
// <div class=".box">Literal dot-box</div>
$("div").removeClass("highlight");
// Match class=".box" only — not class="box"
$("." + $.escapeSelector(".box")).addClass("highlight");
The leading . in "." + $.escapeSelector(".box") is the class combinator. escapeSelector escapes the dot inside the name so the engine reads the full string .box as the class value, not “class box.”
Example 3 — Class .list vs Plain list
Distinguish list items with class list from the unusual case where the class attribute is literally .list.
$(".list") would match two elements with class list. Escaping targets the one element whose class string includes the leading dot as data, not as syntax.
Example 4 — Id #list vs Plain list
Select the list item whose id attribute is literally #list, not id="list".
Pass the full id value including its hash to escapeSelector, then prepend one # for the id combinator. The escaped hash inside the identifier prevents Sizzle from stopping at the first special character.
Example 5 — Build a Safe Selector from User Input
Read a class name from an input field, escape it, and query the page without selector injection bugs.
jQuery
function findByClassName(name) {
var safeSelector = "." + $.escapeSelector(name);
console.log("Built selector:", safeSelector);
$(".tag").removeClass("match");
$(safeSelector).addClass("match");
return $(safeSelector).length;
}
// User types "item.main" — dots are escaped automatically
findByClassName("item.main"); // Built selector: .item\.main
User-controlled strings must never flow directly into $(). Escaping neutralizes dots, hashes, brackets, and other characters that could change selector meaning or cause unexpected matches across the document.
Applications
🚀 Common Use Cases
CMS-generated class names — frameworks sometimes emit classes with dots, colons, or brackets that break naive $("." + name) concatenation.
Widget configuration — escape id or class values read from data-* attributes before querying child elements.
Search / filter UIs — highlight tags or categories when users pick labels containing special characters.
Legacy markup — support HTML where ids or classes were copied from CSS selectors literally, including leading # or ..
Plugin development — accept arbitrary class hooks from consumers without documenting “avoid dots” restrictions.
Testing & debugging — verify Sizzle matches the same elements as attribute-based queries on oddball identifiers.
🧠 How jQuery.escapeSelector() Prepares a String
1
Receive identifier
jQuery accepts the raw string — a class name, id value, or fragment — that may contain CSS syntax characters.
Input
2
Scan for specials
Characters like #, ., [, ], and : are flagged as needing escape sequences for Sizzle.
Parse
3
Insert backslashes
Each special character is prefixed with \ so the selector engine reads it as literal text.
Escape
4
🔎
Concatenate & query
Prepend . or #, pass to $(), and Sizzle matches the intended elements safely.
Important
📝 Notes
Available since jQuery 3.0; still supported in current 3.x — not deprecated.
Static utility only: $.escapeSelector(str) — there is no .escapeSelector() on collections.
You must still add the combinator (. or #) when building class or id selectors.
For exact attribute matching, [class="value"] or [id="value"] can work but require careful quoting of quotes inside values.
Native CSS.escape() escapes identifiers for CSS contexts; behavior is similar but not identical to Sizzle’s expectations in every edge case.
Escaping does not validate that the selector exists in the DOM — it only makes the syntax safe.
Compatibility
Browser Support
jQuery.escapeSelector() ships with jQuery since 3.0+. It depends on jQuery, not on a separate polyfill. Native CSS.escape() is available in modern browsers as an alternative for identifier escaping outside jQuery.
✓ jQuery 3.0+
jQuery jQuery.escapeSelector()
Requires jQuery 3.0 or later. Works wherever jQuery 3.x runs — all browsers jQuery supports. CSS.escape() is native in Chrome 46+, Firefox 31+, Safari 9.1+, Edge, and current runtimes.
100%jQuery 3.x support
Google ChromeAll versions · Desktop & Mobile
Full support
Mozilla FirefoxAll versions · Desktop & Mobile
Full support
Apple SafariAll versions · macOS & iOS
Full support
Microsoft EdgeAll versions · Chromium & Legacy
Full support
Internet ExplorerIE 6+ · Legacy environments
Full support
OperaAll modern versions
Full support
jQuery.escapeSelector()Since 3.0
Bottom line: Use $.escapeSelector() whenever you concatenate variable class or id names into jQuery selectors. Upgrade to jQuery 3+ if your project still targets 1.x/2.x and needs this API.
Wrap Up
Conclusion
The jQuery.escapeSelector() utility solves a narrow but painful problem: selecting elements whose class or id values contain characters that CSS treats as syntax. By escaping those characters before you build a selector string, you avoid silent mismatches and unsafe dynamic queries.
Remember that it is a static helper on jQuery, available since version 3.0, and that you still prepend . or # yourself. For user-driven lookups, always escape first — never pass raw input to $().
Escape every variable fragment before concatenating into $()
Use "." + $.escapeSelector(name) for classes and "#" + ... for ids
Prefer $.escapeSelector in jQuery 3+ codebases for Sizzle compatibility
Log built selectors during development to verify escaping
Consider attribute selectors when matching exact attribute strings
❌ Don’t
Call $(userInput) with unescaped user or CMS data
Assume $(".name") matches class=".name"
Chain .escapeSelector() on a jQuery collection — it does not exist
Hand-roll regex escapes and miss brackets, colons, or spaces
Forget the leading . or # after escaping
Summary
Key Takeaways
Knowledge Unlocked
Five things to remember about jQuery.escapeSelector()
Escape first, concatenate second, query last.
5
Core concepts
🔎01
$.escapeSelector
Static utility
API
🔢02
Since 3.0
jQuery 3.0+
Version
🗃03
Literal dots
class=".box"
Use case
⚠04
Not chained
No .escapeSelector()
Static
✅05
User input
Escape before $()
Safety
❓ Frequently Asked Questions
jQuery.escapeSelector(selector) takes a string and returns a version safe to embed inside a CSS selector. It escapes characters that have special meaning in CSS — such as #, ., [, ], :, and others — so jQuery's Sizzle engine treats them as literal text instead of syntax. You still prepend . or # when building class or id selectors; escapeSelector only escapes the identifier portion.
jQuery.escapeSelector() was added in jQuery 3.0. It is a static utility on the jQuery/$ namespace — call $.escapeSelector(str), not $(collection).escapeSelector(). You need jQuery 3.0 or later; it remains available in current 3.x releases and is not deprecated.
Both escape identifiers for CSS contexts, but CSS.escape() is a native browser API (ES2015) that escapes a single identifier value. jQuery.escapeSelector() is tailored for strings you splice into jQuery selector expressions and handles edge cases Sizzle expects. In jQuery code, $.escapeSelector() keeps selector building consistent; outside jQuery, CSS.escape() or attribute selectors are alternatives.
In CSS, . starts a class selector and # starts an id selector. A class name literally named .box is not the same as class="box". Writing $(".box") searches for class="box"; to match class=".box" you need $("." + $.escapeSelector(".box")). The same applies to id="#list" versus id="list" — escape the hash before concatenating into "#" + escaped.
It is static — jQuery.escapeSelector(selector) or $.escapeSelector(selector). It is not chained on a jQuery collection like $("div").escapeSelector(). Think of it alongside $.trim() or $.proxy(): a helper on the jQuery object itself that returns a string, not a jQuery object.
Never concatenate raw user input into $(userValue). Escape first: var safe = "." + $.escapeSelector(name); then $(safe). For ids use "#" + $.escapeSelector(id). Characters like dots, hashes, brackets, colons, spaces, and punctuation in generated CMS class names all need escaping. When matching exact attribute values instead, $("[class='" + value.replace(/'/g, "\\'") + "']") avoids some selector syntax issues but escapeSelector is the idiomatic jQuery 3+ approach for class/id fragments.
Did you know?
Before jQuery 3.0, developers often used attribute selectors like [id="#list"] or brittle regular expressions to match ids and classes containing hashes and dots. jQuery’s Sizzle engine gained $.escapeSelector() so the same escaping rules live in one tested utility — the same release line that dropped support for older Internet Explorer versions and embraced modern browser standards.