Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery Syntax error, unrecognized expression:

Tags:

Why do I get this error and how can I test for it so it wont break, I tried checking for null but obviously that wont work, thanks.

Please don't advice to not write the ID like this as I know its wrong but it is a possibility.

var jsonTest = [
  {
    "myId": "''''''\"\"\"\"'''''''''''''\"#####$'''''",
  }
];

alert(jsonTest[0].myId); 
// Works - alerts the myId

$('#' + jsonTest[0].myId ).length; 
// Error: Syntax error, unrecognized expression:
// #''''''""""'''''''''''''"#####$'''''
like image 200
Hello-World Avatar asked Mar 11 '13 12:03

Hello-World


1 Answers

jQuery's uses this code to detect an id based selector :

characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+"
...
"ID": new RegExp( "^#(" + characterEncoding + ")" ),

This regex fails for "''''''\"\"\"\"'''''''''''''\"#####$'''''" or more simply for "'".

The query engine is limited, which isn't very surprising for a so concise language and id validity rules so lax. it can't handle any valid id.

If you really need to be able to handle any kind of valid id, use

$(document.getElementById(jsonTest[0].myId))

In fact, you should never use $('#'+id) as it simply adds a useless (and a little dangerous) layer of parsing for the same operation.

like image 164
Denys Séguret Avatar answered Sep 22 '22 04:09

Denys Séguret