Escaping characters to get a valid jQuery id

jQuery is a very powerful javascript library that I use all the time. For the most part, I find that it's simple to use, yet easy enough to do very advanced things. Anyone who has used jQuery knows that you can do quite a lot with selectors. One of the caveats that I run into often is using a selector for a DOM element that contains special characters. jQuery requires many characters to be escaped in the selector in order to function properly. The problem here is that jQuery doesn't offer a function that will escape your selector value for you. I've created such a function here:

  1. // Escapes special characters and returns a valid jQuery selector
  2. function jqSelector(str)
  3. {
  4. 	return str.replace(/([;&,\.\+\*\~':"\!\^#$%@\[\]\(\)=>\|])/g, '\\$1');
  5. }

If you want to use the jqSelector() function, you can do so like this:

The HTML
<div id="id.with,special#characters" class="testElem[1]"></div>

The javascript

  1. // ID selector
  2. $('#'+jqSelector('id.with,special#characters')).text('My Selected Element');
  3.  
  4. // Class selector
  5. $('.'+jqSelector('testElem[1]')).text('My Selected Element');

This simple function will do the work of escaping all the characters you need to form a proper jQuery selector. Enjoy!

Attached Files: