Skip to content

Instantly share code, notes, and snippets.

@djcsdy
Created March 24, 2011 16:58
Show Gist options
  • Save djcsdy/885418 to your computer and use it in GitHub Desktop.
Save djcsdy/885418 to your computer and use it in GitHub Desktop.
Escapes a string for use within a CSS selector as an identifier
function escapeSelector(selector) {
return "".replace.call(selector,
/(^[^_a-zA-Z\u00a0-\uffff]|[^-_a-zA-Z0-9\u00a0-\uffff])/g,
"\\$1");
}
// Use this to escape CSS identifiers that may contain reserved characters.
// For example, in JQuery, to select the element whose identifier is named by the variable 'id':
$('#' + escapeSelector(id));
// This works even if 'id' is something crazy like '+-~/!"£$%^&*([]'.
@marcusflat
Copy link

I've tried CSS.escape but didn't fit well, but thanks for all recommendations !!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment