"If you wish to use any of the meta-characters ( such as !"#$%&'()*+,./:;<=>?@[\]^`{|}~ ) as a literal part of a name, you must escape the character with two backslashes: \\."
Unfortunately, jQuery doesn't offer any function to escape these characters within a string, so that you don't have to care about what characters you must not use when defining attributes of your markup.
So I've spent almost one hour playing (or better fighting) with regular expressions in order to create a general function to escape strings to use in jQuery selectors. So if you're an absolutely RegEx guru or just have the time to figure out the right regular expression to use for this purpose, then you're probably not so interested in the following function. Otherwise, you should really try it out! ;)
function jQuerySelectorEscape(expression) {
return expression.replace(/[!"#$%&'()*+,.\/:;<=>?@\[\\\]^`{|}~]/g, '\\$&');
}
The function inserts a backslash before all meta-characters for jQuery selectors within a string.
Here's an example:
<div id="my#div$has[some]strange*characters">My DIV</div>
<br/>
<script type="text/javascript">
var selector = '#' + jQuerySelectorEscape('my#div$has[some]strange*characters');
document.write('selector = ' + selector);
document.write('<br/><br/>');
document.write('DIV content = ' + jQuery(selector).html());
</script>Output:My DIV selector = #my\#div\$has\[some\]strange\*characters DIV content = My DIV
I hope you can avoid some headaches with this function. If there's any question or problem with it, leave a comment below and I'll try to help you out.

