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:
// #''''''""""'''''''''''''"#####$'''''
Stan James
2,5151 gold badge28 silver badges35 bronze badges
asked Mar 11, 2013 at 12:36
Hello-WorldHello-World
9,18923 gold badges87 silver badges153 bronze badges
0
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.
answered Mar 11, 2013 at 12:39
Denys SéguretDenys Séguret
370k85 gold badges775 silver badges752 bronze badges
3
If I understood your question, you have an ID that contains special characters. You basically need to escape them so they’re treated as literal characters rather than query selectors:
To use any of the meta-characters ( such as
!»#$%&'()*+,./:;<=>?@[]^`{|}~ ) as a literal part of a name, it must
be escaped with with two backslashes: . For example, an element with
id=»foo.bar», can use the selector $(«#foo.bar»).
… and in this case you also need an additional escaping level for the string delimiter, "
. It’s crazy but this works:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head><title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript"><!--
jQuery(function($){
console.log( $("#" + "\'\'\'\'\'\'\"\"\"\"\'\'\'\'\'\'\'\'\'\'\'\'\'\"\#\#\#\#\#\$\'\'\'\'\'").length );
});
//--></script>
</head>
<body>
<div id="''''''""""'''''''''''''"#####$'''''">Foo</div>
</body>
</html>
Edit: Of course, dystroy’s answer —omit jQuery selection engine and use getElementByID()
— is way more practical. jQuery manual links an interesting blog entry that covers this and other related techniques:
document.getElementById() and similar functions like
document.getElementsByClassName() can just use the unescaped attribute
value, the way it’s used in the HTML. Of course, you would have to
escape any quotes so that you still end up with a valid JavaScript
string.
answered Mar 11, 2013 at 13:07
Álvaro GonzálezÁlvaro González
141k40 gold badges259 silver badges356 bronze badges
W3C has defined a new function for this this: CSS.escape()
. In your example code, it would look like this:
var jsonTest = [
{
"myId": "''''''""""'''''''''''''"#####$'''''",
}
];
$('#' + CSS.escape(jsonTest[0].myId)).length; // Works
Browsers don’t yet support it, but there is a polyfill library that you can use in the mean time:
https://github.com/mathiasbynens/CSS.escape
I’ve used it with success in my project.
answered Sep 30, 2015 at 17:54
I faced this error while upgrading from jquery 1.6 to jquery 3.6.
I got this error in flexigrid library. The fix to this problem is simple as mentioned in above answers.
You need to escape all special characters and unescape them if needed to show in a grid or for further processing.
The code looks like:
var str = "abc@abc.com";
//make str value to, basically escape all special chars : "abc/@abc/.com"
str = str.replace(/[.*+?^$@%{}()|[]\]/g, '\$&');
//do some processing
//revert str value to: "abc@abc.com"
str = str.replaceAll("\", "");
answered May 11, 2021 at 10:39
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
- Pick a username
- Email Address
- Password
By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.
Already on GitHub?
Sign in
to your account
Доброго времени суток, возникло 2 вопроса.
1) при клике на логотип сайт, который имеет якорь «#» и отправляет на верх сайт, выдаётся ошибка.(ругается на 4-ю строчку)
Текст ошибки:
Uncaught Error: Syntax error, unrecognized expression: #(…) — «jquery.js?ver=1.12.4:2
2) В 8й строке, у меня происходит переход на главную страницу и мне нужно выполнить оставшийся код, который идёт после else. Проблема в том, что этот код выполняется моментально, а мне нужно сделать так, чтобы он выполнялся только после того, как произойдёт переход на страницу.
jQuery(function($) {
var homepage = 'http://rcamedia.ru/';
$('a[href*=#]').live('click', function(event) {
var attrib = $(this).attr('href');
console.log(attrib);
if($("div").is(attrib)) {}
else {
document.location = homepage;
}
event.preventDefault();
var target_offset = $(this.hash).offset() ? $(this.hash).offset().top : 0;
//change this number to create the additional off set
var customoffset = 85;
$('html, body').animate({scrollTop:target_offset - customoffset}, 500);
console.log("Done!");
});
}(jQuery));
Answer by Vienna Greer
If you are using jQuery1.9, the problem may lie in the content being loaded. There is a new update which requires that the first character in the response be a < [AKA the less than symbol]. Even whitespace will cause this to break and throw the dreaded «Uncaught Error: Syntax error, unrecognized expression:» error.,Find centralized, trusted content and collaborate around the technologies you use most.,
Will the net current drawn by a microcontroller equal the current supplied by it
,Asking for help, clarification, or responding to other answers.
If I’m doing that :
$.ajax('/',function(html){
html = $('<div></div>').append(html);
$(html);
});
It works fine.
If I do :
$.ajax('/',function(html){
$(html);
});
It gives me a (through the FF error console) :
Erreur : Error: Syntax error, unrecognized expression: <div id="...">(...)
jquery.min.js - line : 4
So I now do something like :
$.ajax('/',function(html){
$($.parseHTML(html));
});
Answer by Aydin Ibarra
I’m trying to retrieve data through .ajax call and add the response html code to bootstrap modal body. But I kept receiving this error:,Actually I do receive the desired data in response, but because of this error, the data cannot be displayed on modal window. ,Here is my code. When I click a link, the ajax call returns a html form and inserts it into modal body. Then the modal window is shown.,I have been googling and changing the code for several hours but still no luck. I would highly appreciate it if anyone can give me some idea. Thanks in advance!
Here is my code. When I click a link, the ajax call returns a html form and inserts it into modal body. Then the modal window is shown.
<a href="{{route('menu.create')}}" class="btn btn-default pull-right show-new-menu-item-modal" data-toggle="modal">New Menu Item</a>
$('body').on('click', '.show-new-menu-item-modal', function(event) {
event.preventDefault();
$.ajax({
url: $(this).attr('href'),
dataType: 'html',
success: function(response) {
$("#new-menu-item-body").html(response);
}
});
$('#new-menu-item-modal').modal('show');
});
Answer by Daniella Beil
© 2013 jQuery Foundation
<html><body><div id="error">Desolee, Adresse e-mail incorrect.Desolee, Entrez votre nom</div></body></html>
Answer by Wallace English
How to I resolve unrecognized expression?,If I use Java’s ‘MediaServletTree’, I get ‘Uncaught Error: Syntax error, unrecognized expression: {“id”:“demo_child_1”,“text”:“Child 1”}’.,Powered by Discourse, best viewed with JavaScript enabled,My code in Java for MediaServletTree:
My javascript:
$('#treeFolderName').jstree({
"core" : {
'data' : {
'url' : function (node) {
return node.id === '#' ?
'../MediaServletTree' : '../MediaServletTree';
//'ajax_demo_children.json' : 'ajax_demo_children.json';
},
'data' : function (node) {
return {
'id' : node.id
};
}
}
}
});
My code in Java for MediaServletTree:
JSONObject jsonObj = new JSONObject();
jsonObj.put("id", "demo_child_1");
jsonObj.put("text", "Child 1");
out.print(jsonObj);
Answer by Jedidiah Rhodes
Parsing jQuery Ajax response
,
JQuery and Ajax response headers
,
ajax — Parsing JSON response using jquery
,this is the output of console.log(success); and the red box is what I want from the response…
I need to post data to a php page and then I’d like to get the text of a certain div that is in the response but I can’t seem to set things up correctly. I’m not too good with jQuery but I can usually figure things out fairly quickly… I’ve been at this for a minute and have tried everything I have found… I think I am just missing the right combination of stuff.
$.post("process.php", data , function (response) {
var w = window.open();
$(w.document.body).html(response);
console.log(typeof response); // yeilds string
//create jquery object from the response html
// var $data = $(response); // yeilds Uncaught Error: Syntax error, unrecognized expression: + whole html text
var success = $($.parseHTML(response)).find("#success");
console.log('success');
console.log(success); // see screenshot
console.log(success.text()); // yields nothing
console.log(success.val()); // yields undefined
// if (window.focus) {w.focus()};
},'html');
and this does that:
var success = $(response).find("#success");
console.log('success');
console.log(success); // yeilds Uncaught Error: Syntax error, unrecognized expression: + whole html text in red
Response is…
<html><head>
<style>
div.totals {
font-family:calibri; font-size:.9em; display:inline-block;
border-width: 2px; border-style: solid; border-color: #FFD324;
background-color: #FAF5D7; color: #514721;
width: 500px;
}
div.error_invalid {
font-family:calibri; font-size:.9em; display:inline-block;
border-width: 2px; border-style: solid; border-color: #9999CC;
background-color: #EEEEFF; color: #7979B8;
}
</style>
</head>
<body>
<div class="totals">Total new rows added: 0 out of 0<br/></div>
<br/><br/>
<div class="totals">Total updated rows: 0 out of 0 <br/></div>
<div id="success">true</div>
</body></html>
Answer by Presley Portillo
3. Although the error handler .fail()is defined, you will still see the syntax error Uncaught Error: Syntax error, unrecognized expression: {«code»:»rest_no_route»,»message»:»No route was found matching the URL and request method»,»data»:{«status»:404}},Now if you deactivate Wordfence, the request error will gracefully be handled.,Steps to reproduce:
1. Open the console in wp-admin with Wordfence active.
2. Run this code which results in an error (404), because of v1 instead of v2,I did a bit of snooping myself and found the exact line where the error is raised:
Steps to reproduce:
1. Open the console in wp-admin with Wordfence active.
2. Run this code which results in an error (404), because of v1 instead of v2
jQuery.ajax({
type: 'GET',
url: location.origin + '/wp-json/wp/v1/posts',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
})
.then(data => console.log(data))
.fail(jq => console.log(jq));
Answer by Matteo Hail
With the conversion to Editor 1.5, I am unable to edit any rows. I get errors like:,What is really interesting is that jQuery’s selectors shouldn’t actually be getting invoked at all here with the latest DataTables versions.,As a little workaround for the moment, could you try the following — in the dataTables.editor.js file find:,Thanks for the workaround code, Allan. I haven’t tried it yet since I am using a single, minified file from the awesome new DataTables Downloader.
AJAX Load:
{
"draw" : 1,
"recordsTotal" : 3,
"recordsFiltered" : 3,
"data" : [
[
"{"P":"AAAX88AAJAAAAGXAAA","K":{"ID":1}}",
1,
"Administrator",
"TableMan Administrators-1"
],
[
"{"P":"AAAX88AAJAAAAGXAAB","K":{"ID":2}}",
2,
"Test Group2",
"Includes a few more tables"
],
[
"{"P":"AAAX88AAJAAAAGXAAC","K":{"ID":3}}",
3,
"3rd Groupx2",
"Includes yet more tables"
]
]
}
Request:
{
"action" : "edit",
"data" : {
"{"P":"","K":{"Id":4}}" : {
"EditorId" : "-6",
"AccountId" : "1",
"EventType" : "L",
"LogSqlId" : "0",
"LogIpAddressId" : "1",
"UtcTime" : "09/02/2015 4:59 PM"
}
}
}
Response:
{
"data" :
[
[
"{"P":"","K":{"Id":4}}",
4,
-6,
1,
"L",
0,
1,
"2015-09-02T16:59:00"
]
]
}
Chrome’s trace (at least, it looks like a trace to me):
Uncaught Error: Syntax error, unrecognized expression: #{"P":""
Sizzle.error @ jquery-2.1.4.js:1458
Sizzle.tokenize @ jquery-2.1.4.js:2075
Sizzle.compile @ jquery-2.1.4.js:2446
Sizzle.select @ jquery-2.1.4.js:2536
Sizzle @ jquery-2.1.4.js:855
Sizzle.matches @ jquery-2.1.4.js:1396
jQuery.filter @ jquery-2.1.4.js:2672
winnow @ jquery-2.1.4.js:2655
jQuery.fn.extend.filter @ jquery-2.1.4.js:2704
(anonymous function) @ tm.min.js:175Za @ tm.min.js:172
(anonymous function) @ tm.min.js:174
h.extend.iterator @ tm.min.js:162
(anonymous function) @ tm.min.js:174
t.extend.g @ tm.min.js:165
(anonymous function) @ tm.min.js:178
t.extend.g @ tm.min.js:165
E.dataTable.commit @ tm.min.js:424
f._dataSource @ tm.min.js:402
(anonymous function) @ tm.min.js:415
(anonymous function) @ Editor?id=9:83
jQuery.Callbacks.fire @ jquery-2.1.4.js:3099
jQuery.Callbacks.self.fireWith @ jquery-2.1.4.js:3211
done @ jquery-2.1.4.js:8264
jQuery.ajaxTransport.options.send.callback @ jquery-2.1.4.js:8605
browserLink:37 XHR finished loading: GET "http://localhost:61071/dc7f0afe6d5c4ba592d097da5a0d5fca/arterySignalR/ping?…KHTML%2C+like+Gecko)+Chrome%2F45.0.2454.85+Safari%2F537.36&_=1442619094666".p.support.ajax.p.ajaxTransport.c.send @ browserLink:37p.extend.ajax @ browserLink:37i.transports._logic.pingServer @ browserLink:62(anonymous function) @ browserLink:62
Answer by Lucian Melton
If the AJAX response have some space before the HTML start tag
jQuery will throw this error.
Emmmmmmm…, I found two way to fix it, make sure server response <!DOCTYPE HTML> as response first start string,
or plugin trim the response string before call
e = $(this.itemsContainerSelector, b.trim()).eq(0),Thank you for your report. I don’t want to bloat the plugin with fixes for everything that can go wrong with a website, but I will take it into consideration.,
Uncaught Error: Syntax error, unrecognized expression: <!DOCTYPE HTML> when has space before <!DOCTYPE HTML>
,If you have questions, feedback or think this issue was closed by mistake, please comment on this issue.
If the AJAX response have some space before the HTML start tag
jQuery will throw this error.
Emmmmmmm…, I found two way to fix it, make sure server response <!DOCTYPE HTML>
as response first start string,
or plugin trim the response string before call
e = $(this.itemsContainerSelector, b.trim()).eq(0)
<!DOCTYPE HTML>
If the AJAX response have some space before the HTML start tag
jQuery will throw this error.
Emmmmmmm…, I found two way to fix it, make sure server response <!DOCTYPE HTML>
as response first start string,
or plugin trim the response string before call
e = $(this.itemsContainerSelector, b.trim()).eq(0)
e = $(this.itemsContainerSelector, b.trim()).eq(0)
Let’s face it, nobody is perfect! Everyone makes mistakes now and then and jQuery is the same – although they have an excellent bug fixing team who are fixing up errors and enhancing jQuery around the clock errors may appear from time to time.
In light of this and the fact that I’ve been developing with jQuery for quite a while now and every now and then an error will show in the Firebug Console and “I have to Google it”. I thought I would share some of the most common jQuery errors so that when you encounter them you might have some idea of how to solve the puzzle.
Error: “jquery.1.4.2.js error “a is null””
Possible Causes
a is null
[Break On This Error] a))();else c.error("Invalid JSON: "+a)...(d)if(i)for(f in a){if(b.apply(a[f],
jquery....min.js (line 29)
I was thinking it might have something to do with this line failing because there was no matches.
$.each(rawData.match(secureQueryRegex), function(index, currentQuery)
Then, I was thinking it may have been the size of data as it was 69,443 characters long…
Possible Solutions
But I eventually found out it was bad characters inside the data string (which was grabbed directly from HTML). See cleanHTML() function to remove bad characters form HTML.
rawData = rawData.replace(/[^<>a-zA-Z 0-9]+/g,''); /* clean up for match() statement */
Specific Versions
Seen in 1.4.2
Error: “SyntaxError: invalid object initializer”
Possible Causes
Object declaration syntax error.
$.getScript(
{
'http://www.domain.com/js/preview.js'
});
OR
$("div").css(
{
padding:'0',
margin,'4px'
});
Possible Solutions
Remove the brackets the getScript() function can be called with just the url. The same applies to any other object declaration or function call with an object that doesn’t accept one.
$.getScript('http://www.domain.com/js/preview.js');
Change the comma to a semi colon.
$("div").css(
$("div").css(
{
padding: '0',
margin: '4px'
});
Specific Versions
Seen in 1.4.2
Error: “uncaught exception: Syntax error, unrecognized expression: [object HTMLLIElement]”
Possible Causes
This seems like a jQuery selector error. It seems to appear more frequently in v1.4.2 or earlier so try updating to the latest version of jQuery.
$(this+' a').css(
var req = $("input[@name=required]").val();
Possible Solutions
Not sure but take a look at your selectors and make sure they work properly. Try including the full jQuery versions first to get better error info on what might be causing the problem.
@ is old selector syntax.
var req = $("input[name=required]").val();
Specific Versions
Seen in 1.4.2
Error: “SyntaxError: missing ) after argument list”
Possible Causes
Missing off closing brackets or curly braces.
})(jQuery
Possible Solutions
})(jQuery);
Specific Versions
Seen in 1.4.2
Error: “SyntaxError: missing : after property id”
Possible Causes
This is a repeat of the object initialize error but it’s caused by Using curly brackets when they are not needed.
$.getScript(
{
'http://www.domain.com/js/preview.js', function(data, textStatus){
console.log(data); //data returned
console.log(textStatus); //success
console.log('Load was performed.');
});
Possible Solutions
$.getScript('http://www.domain.com/js/preview.js', function(data, textStatus)
{
console.log(data); //data returned
console.log(textStatus); //success
console.log('Load was performed.');
}
);
Specific Versions
Seen in 1.4.2
Error: “TypeError: jsSrcRegex.exec(v) is null”
Possible Causes
Caused by double exec on same regex OR caused by invalid html “jsSrcRegex.exec(v) is null”.
console.log(jsSrcRegex.exec(v));
console.log(jsSrcRegex.exec(v)[1]);
Possible Solutions
Check the html first:
if(jsSrcRegex.exec(html)){
console.dir(jsSrcRegex.exec(html)[1]);
}
OR
Use recompile the regex:
console.log(jsSrcRegex.exec(v));
jsSrcRegex.compile();
console.log(jsSrcRegex.exec(v)[1]);
Specific Versions
n/a
Error: “XML descendants internal method called on incompatiable object”
Possible Causes
Double full stop in jQuery chain commands.
$('.'+inElem)..removeClass('mouseover').addClass('selected');
Possible Solutions
To fix simply remove the double full stop.
Specific Versions
n/a
Error: “undetermined string literal”
You may have seen this one before!
Possible Causes
Many possible causes: could be that you put code where a selector should be or multiple line strings or wrong string format (bad characters) or angle brackets etc.
Possible Solutions
See jQuery Undetermined String Literal Error for a very detailed explanation on this error!
Specific Versions
n/a
Error: “Syntax Error: Unrecognized Expression”
Possible Causes
Missing attribute name in selector.
$('input["depDate"]').val(departureDate);
Possible Solutions
Add in the name attribute (or id, class etc) into the selector.
$('input[name="depDate"]').val(departureDate);
Specific Versions
n/a
Error: “SyntaxError: syntax error”
(click image to enlarge)
Possible Causes
Well, this error is very generic and there might be a number of reasons why is happens but in this example you can clearly see it was caused by an extra “+” in the jQuery selector.
$('.itemColumn'+currentColNum+).append(v);
Possible Solutions
Unfortunately, on this one you’ve just got to carefully check through your syntax and make sure you don’t have any mistakes. Try using something like jshint or another js checker to assist.
$('.itemColumn'+currentColNum).append(v);
Specific Versions
n/a
Error: “(d || “”).split is not a function”
Possible Causes
Sorry, I found this error and took a screenshot but can’t remember how i got it! I think it might be a live image hover bug in jQuery 1.4.2 but not sure.
Here is something bug 862 similar which i found (it was logged 5 years ago aha).
Sometimes you see a similar error which reads “jquery error d is undefined” or such which I saw a few times in jQuery 1.5.
Possible Solutions
Update to latest version of jQuery.
Specific Versions
Seen in 1.4.2
Error: “Syntax error, unrecognized expression: >”
Possible Causes
if ($('#'+$form).length == 0)
{
...
}
if ($('#'+$form))
{
...
}
Possible Solutions
Don’t try to use html as a jQuery selector element.
Specific Versions
Seen in 1.7.1
Error: “Syntax error, unrecognized expression: #[object Object]”
Possible Causes
Using an DOM element as a jQuery selector element.
$('#'+$form)
Possible Solutions
Check your jQuery selectors are correct.
Specific Versions
Seen in 1.7.1
Error: “Syntax error, unrecognized expression: name”
Possible Causes
var code = $(':input:name=["disCode"]').val();
Possible Solutions
Move square bracket before attribute name.
var code = $(':input:[name="disCode"]').val();
Specific Versions
Seen in 1.7.2
Error: “XML descendants internal method called on incompatible Object”
Possible Causes
discElem..parent().after(data.html);
Possible Solutions
discElem.parent().after(data.html);
Specific Versions
Seen in 1.7.2
Error: “SyntaxError: invalid label”
Possible Causes
Using a colon at the end of a statement.
console.log(count):
Possible Solutions
Use a semi colon instead of a colon.
console.log(count);
Specific Versions
Seen in 1.7.2
Error: “TypeError: emails.match(/@/gim) is null”
Possible Causes
Using .length function on a regular expression which has no matches.
var emails = '',
count = emails.match(/@/igm).length;
Possible Solutions
If you reference the length property after then it simply returns undefined and no error. If you use the following you will see the error: “TypeError: count is null”.
var emails = '',
count = emails.match(/@/igm),
length = count.length;
If you check the count is not null before assigning the value it does not error and will give you 0 for a no count.
var emails = '',
regex = /@/igm,
count = emails.match(regex),
count = (count) ? count.length : 0;
Specific Versions
Seen in 1.7.2
Error: Error in Actionscript. Use a try/catch block to find error.”
Possible Causes
Using a call on a Flowplayer or Flash based Object with errors.
$f('fms2').toggleFullscreen();
Possible Solutions
Try checking the initialisation code for the Flash Object.
Specific Versions
Seen in 1.7.2
After seeing all those errors, here’s something to cheer you up!
Or you can see more errors and bugs on the Official jQuery Bug Tracker.
If you find any errors please leave a comment with the error and solution and i will add it to the list!
Cheers!