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

Nice ! 10 year after and this solution helped me !

Thanks

@djcsdy
Copy link
Author

djcsdy commented Jul 21, 2020

Nowadays you might consider using cssesc, or the experimental CSS.escape API which is supported by all modern browsers.

@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