Does anyone know how to escape the square bracket character when setting a class name with jQuery?
Try the following:
$(\'#txtFirstname\').addClass(\
Short answer: you don't need to escape brackets because the argument is a class name, not a selector. It didn't work for you because of a bug in earlier jQuery versions that has long been fixed.
To demonstrate it, here's your code running under different versions:
$('#txtFirstname').addClass('test[someval]')
$('#txtFirstname').attr('class')
console.log($('#txtFirstname').hasClass('test[someval]'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<div id="txtFirstname"></div>
$('#txtFirstname').addClass('test[someval]')
$('#txtFirstname').attr('class')
console.log($('#txtFirstname').hasClass('test[someval]'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.4.0/jquery.min.js"></script>
<div id="txtFirstname"></div>
So the issued was apparently fixed on jQuery/1.4.0. I found a ticket regarding this (though it's tagged as being fixed on 1.4.2 rather than 1.4.0).
I insist: the rule to quote or escape metacharacters with \\ in order to use them as a literal part of a name only applies to selectors. However, the .hasClass() method does not receive a selector as argument but as class name:
.hasClass( className ) className Type: String The class name to search for.
The introduction of jQuery API page gives the above explanation about this:
To use any of the meta-characters ( such as !"#$%&'()*+,./:;<=>?@[]^`{|}~ ) as a literal part of a name, it must be escaped with with two backslashes: \\.
Escape with TWO (2) backslashes.
http://learn.jquery.com/using-jquery-core/faq/how-do-i-select-an-element-by-an-id-that-has-characters-used-in-css-notation/
If the selector is contained within a variable (or if you can get it into a variable), the code below may be helpful:
selector_name = $this.attr('class');
//e.g selector_name = users[0][first:name]
escaped_selector_name = selector_name.replace(/(:|\.|\[|\])/g,'\\$1');
//e.g escaped_selector_name = users\\[0\\]\\[first\\:name\\]
In short we prefix all special characters with double backslash. Here's some additional documentation from the jQuery site:
http://learn.jquery.com/using-jquery-core/faq/how-do-i-select-an-element-by-an-id-that-has-characters-used-in-css-notation/