Jquery selector not accept pipe character |?

I have an html id I'm trying to call. It has a specific name like this name_|_anyting but when I try to get elemetn using jquery selectors I get an error

 $("#name_|_anyting") 

Error: syntax error, unrecognized expression: | _anyting

so my question is: Are pipe characters allowed in identifiers in jquery selectors?

+7
source share
3 answers

| is a special character in the selector syntax, which means that you cannot use it directly in the identifier selector. If you cannot change the identifier in your markup to place your selector, you will have to do with escaping the selector to trick jQuery anyway:

 $("#name_\\|_anything") 
+11
source

Pipe symbol "|" must be escaped using a double backslash.

Selectors

Borrowing from CSS 1-3 and then adding your own, jQuery offers a powerful set of tools to map a set of elements in a document.

If you want to use any of the metacharacters (for example,! "# $% & '() * +,. / :; <=>? @ [] ^` { | } ~ ****) as the literal part of the name, you should escape the character with two backslashes: \\. For example, if you have an element with id = "foo.bar", you can use the $ selector ("# foo \\. bar"). The W3C CSS specification contains a complete set CSS rules for proper CSS selectors, and a Mathias Bynens blog post about CSS escape sequences for identifiers is also useful.

http://api.jquery.com/category/selectors/

+5
source

To update the old question ... In jQuery 3.0 you can now use $. escapeSelector (selector) . Examples:

 $('#' + $.escapeSelector('crazy|id.selector') + 'Wrapper').show(); $('.' + $.escapeSelector(divClassVariable)).each(function() {...}) 

and (from documents)

 $( "div" ).find( "." + $.escapeSelector( ".box" ) ); 
0
source

All Articles