escaping special characters in jQuery selector

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

In jQuery

 

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:

The function can be used like:

Another function is also here for escaping special characters in jQuery selector :

You Might Interested In

1 COMMENT

Leave a Reply

Enclose a code block like: <pre><code>Your Code Snippet</code></pre>.