jQuery is a very powerful JavaScript library that We use all the time. 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 found is using a selector for a DOM element that contains special characters which need to be escaped first.
Escaping special characters in jQuery selector
Because jQuery uses CSS syntax for selecting elements, some characters are interpreted as CSS notation. For example, ID attributes, after an initial letter (a-z or A-Z), may also use periods and colons, in addition to letters, numbers, hyphens, and underscores. The colon :
and period .
are problematic within the context of a jQuery selector because they indicate a pseudo-class and class, respectively. jQuery requires many characters to be escaped in the selector in order to function properly.
In order to tell jQuery to treat these characters literally rather than as CSS notation, they must be escaped by placing two backslashes \\
in front of them.
The HTML
1 | <div id="example:id" class="testElem[1]"> </div> |
In jQuery
1 2 3 4 5 | // Does not work: $( "#example:id" ) // Works! $( "#example\\:id" ) |
1 2 3 4 | // Does not work: $( ".test.class" ) // Works! $( ".test\\.class" ) |
So as above given example we can use 2 backslashes for escaping special characters in jQuery selector. But we can create a simple function to take care of escaping these characters and places a #
at the beginning of the ID string:
1 2 3 | function jqSelector( id ) { return "#" + id.replace( /(:|\.|\[|\]|,)/g, "\\$1" ); } |
The function can be used like:
1 | $( jqSelector( "example.id" ) ) |
Another function is also here for escaping special characters in jQuery selector :
1 2 3 4 5 6 | function jqSelector(str) { return str.replace(/([;&,\.\+\*\~':"\!\^#$%@\[\]\(\)=>\|])/g, '\\$1'); } $('#'+ jqSelector( "example.id" ) ).text('My Selected Element') |
Thank you!!!!