Syntax error unrecognized expression nan

Common jQuery errors that you might see in the firebug console and how to fix them - "a is null", "invalid object", "SyntaxError" and "invalid object".

jquery-errors-post

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””

jquery.1.4.2-error

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”

invalid-object-init

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]”

syntax-error

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”

no-idea

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”

mssing-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”

xml-error

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! :)
string-error

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”

jquery-error-unrecognised-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”

string-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”

live-hover-error

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: >”

error1b

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]”

error2

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”

error-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”

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”

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”

TypeErroremailsmatch

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!

smiley-face

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!


MadHatter

160 / 146 / 57

Регистрация: 15.06.2013

Сообщений: 1,065

1

16.01.2014, 01:18. Показов 11977. Ответов 2

Метки нет (Все метки)


Здравствуйте. Столкнулся с проблемой. Есть такой код:

Javascript
1
2
3
4
for (var j = 0; j < 6; j=j+6) {
    var aaa = "'.every_new_" + j + "'";
                 alert ($(aaa).height());
    }

Переменная aaa — string. В консоли выводится ошибка:
Error: Syntax error, unrecognized expression: ‘.every_new_0’
throw new Error( «Syntax error, unrecognized expression: » + msg );
Подскажите пожалуйста, что означает эта ошибка и что не так в выборке?



0



Lazy_Den

3322 / 2842 / 1423

Регистрация: 15.01.2014

Сообщений: 6,170

16.01.2014, 02:17

2

Перемудрили с кавычками.

Javascript
1
var aaa = '.every_new_' + j;

И я бы вам предложил немного другой способ — не отбирать элементы в цикле, а перебирать массив элементов, отсортировывая их по заданному условию. Например, таким способом.

Javascript
1
2
3
4
var paramsHeight = $('div[class^=every_new_]').map(function(i,el){
    if(i < 6) return $(el).height();
}).get();
console.log(paramsHeight);

Только я не совсем понял, как у вас сочитается условие и инкремент в цикле: j < 6 и j = j + 6 (или j += 6) == одна итерация



0



160 / 146 / 57

Регистрация: 15.06.2013

Сообщений: 1,065

18.01.2014, 11:30

 [ТС]

3

Спасибо за помощь. Но я, все таки, решил сделать немного по-другому. А по поводу цикла, то это только для примера и чтобы цикл быстрее проходил. А в результате там будет много итераций.



0




Форум программистов Vingrad

Модераторы: Sardar, Aliance

Поиск:

Ответ в темуСоздание новой темы
Создание опроса
> Не могу отловить ошибку unrecognized expression: . 

:(

   

Опции темы

mstdmstd
Дата 14.6.2013, 10:26 (ссылка)
| (нет голосов)
Загрузка ... Загрузка …




Быстрая цитата

Цитата

Опытный
**

Профиль
Группа: Участник
Сообщений: 394
Регистрация: 30.12.2008

Репутация: нет
Всего: нет

Всем привет,

на странипе http://www.oherron.com/main/product_listin…ows_in_pager/20
Периодически выскакивает ошибка «Ошибка: uncaught exception: Syntax error, unrecognized expression: .»
Например если в группе слева «Size» выбрать пару элементов(странице перегрузится при каждом выборе размера)
 и потом нажать на появившейся ссылке «Clear Filter».Ошибка похоже выскакивает при переоткрытии страницы
Я искал в коде строку вида

Код

 jQuery('.') 

но такой не оказалось.
В чем может быть проблема?

PM MAIL   Вверх
CruorVult
Дата 14.6.2013, 17:15 (ссылка)
| (нет голосов)
Загрузка ... Загрузка …




Быстрая цитата

Цитата

Опытный
**

Профиль
Группа: Участник
Сообщений: 868
Регистрация: 24.9.2008
Где: г.Киев, Украина

Репутация: 13
Всего: 28

Если включить дебагер, можно увидеть что ошибка здесь 

Код

jQuery("#finish_filter_NYLON.").hover(function(){
        if (document.getElementById("finish_filter_NYLON." ).checked==true) {
          document.getElementById("finish_filter_div_NYLON.").style.backgroundPosition = '0 -45px';
        } else {
          document.getElementById("finish_filter_div_NYLON.").style.backgroundPosition = '0 -15px';
        }
      },function(){
        if (document.getElementById("finish_filter_NYLON." ).checked==true) {
          document.getElementById("finish_filter_div_NYLON.").style.backgroundPosition = '0 -30px';
        } else {
          document.getElementById("finish_filter_div_NYLON.").style.backgroundPosition = '0 0';
        }
      });

Думаю, не стоит использовать точку в id элемета

PM MAIL Skype   Вверх
mstdmstd
Дата 15.6.2013, 09:20 (ссылка)
| (нет голосов)
Загрузка ... Загрузка …




Быстрая цитата

Цитата

Опытный
**

Профиль
Группа: Участник
Сообщений: 394
Регистрация: 30.12.2008

Репутация: нет
Всего: нет

Спасибо  smile 
А подскажите, пожалуйста, а какой дебагер Вы используете ? В моем линуксовом FF 17.0.6 в консоли отображается ошибка -но при клике на ней на строку ошибки она не пререводит…

PM MAIL   Вверх
akizelokro
Дата 16.6.2013, 12:01 (ссылка)
| (нет голосов)
Загрузка ... Загрузка …




Быстрая цитата

Цитата

Крокодил
**

Профиль
Группа: Участник
Сообщений: 761
Регистрация: 30.7.2007

Репутация: 2
Всего: 5

Попробуй ещё Dragonfly, встроенный в Opera

Этот ответ добавлен с нового Винграда — http://vingrad.com

PM MAIL   Вверх
CruorVult
Дата 17.6.2013, 10:00 (ссылка)
| (нет голосов)
Загрузка ... Загрузка …




Быстрая цитата

Цитата

Опытный
**

Профиль
Группа: Участник
Сообщений: 868
Регистрация: 24.9.2008
Где: г.Киев, Украина

Репутация: 13
Всего: 28

Не важно какой дебагер. 
Включаете режим «Pause on all exceptions»(например в Chrome) и смотртите по коллстеку откуда откуда пришла ошибка.

PM MAIL Skype   Вверх



















Ответ в темуСоздание новой темы
Создание опроса

Форум для вопросов, которые имеются в справочниках, но их поиск вызвал затруднения, или для разработчика требуется совет или просьба отыскать ошибку. Напоминаем: 1) чётко формулируйте вопрос, 2) приведите пример того, что уже сделано, 3) укажите явно, нужен работающий пример или подсказка о том, где найти информацию.

 

0 Пользователей читают эту тему (0 Гостей и 0 Скрытых Пользователей)
0 Пользователей:
« Предыдущая тема | JavaScript: Общие вопросы | Следующая тема »

Понравилась статья? Поделить с друзьями:
  • System agent initialization error
  • Syntax error unrecognized expression a href not href
  • Sysprep windows 7 windows произошла неустранимая ошибка
  • Syntax error unit expected but program found
  • Sysprep fatal error occurred while trying to sysprep the machine