Priya
Priya

Reputation: 1481

jQuery: Uncaught Error: Syntax error, unrecognized expression

console.log($('"#'+d+'"'));

In my HTML, I have:

<div id="2013-10-23">
    <h1>5</h1>
    <p>eeeeeeeeeeee</p>
</div>

In the above code, I have one <div> with an id of 2013-10-23, and when getting that id it is throwing this syntax error:

Uncaught Error: Syntax error, unrecognized expression: "#2013-10-23"

Upvotes: 38

Views: 287864

Answers (9)

JSG
JSG

Reputation: 430

I had to look a little more to solve my problem but what solved it was finding where the error was. Here It shows how to do that in Jquery's error dump.

In my case id was empty and `$("#" + id); produces the error.

It was where I wasn't looking, so that helped pinpoint where the issue was so I could troubleshoot and fix it.

Upvotes: 4

Thomas
Thomas

Reputation: 119

I had a selector with space ('#test .test').

Example of my error:

var href = "javascript:scrollto('"+key+"')";

For me this helped: encodeURIComponent(value)

var href = "javascript:scrollto('"+encodeURIComponent(key)+"')";

Upvotes: 0

Teo Mihaila
Teo Mihaila

Reputation: 134

For some people coming here, you might have a special character in your id attribute, so jQuery can't read it correctly.

ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").

Check this answer for more details: What are valid values for the id attribute in HTML?

Upvotes: 0

RDK
RDK

Reputation: 4560

Try this (ES5)

console.log($("#" +  d));

ES6

console.log($(`#${d}`));

Upvotes: 6

Sunil Verma
Sunil Verma

Reputation: 2500

Try using:

console.log($("#"+d));

This will remove the extra quotes you were using.

Upvotes: 7

Martijn
Martijn

Reputation: 16103

The "double quote" + 'single quote' combo is not needed

console.log( $('#'+d) ); // single quotes only
console.log( $("#"+d) ); // double quotes only

Your selector results like this, which is overkill with the quotes:

$('"#abc"') // -> it'll try to find  <div id='"#abc"'>

// In css, this would be the equivalent:
"#abc"{ /* Wrong */ } // instead of:
#abc{ /* Right */ }

Upvotes: 20

Fendi Septiawan
Fendi Septiawan

Reputation: 453

If you're using jQuery 2.1.4 or above, try this:

$("#" + this.d);

Or, you can define var before using it. It makes your code simpler.

var d = this.d
$("#" + d);

Upvotes: 0

OneThreeSeven
OneThreeSeven

Reputation: 422

This can also happen in safari if you try a selector with a missing ], for example

$('select[name="something"')

but interestingly, this same jquery selector with a missing bracket will work in chrome.

Upvotes: 8

webduvet
webduvet

Reputation: 4292

try

console.log($("#"+d));

your solution is passing the double quotes as part of the string.

Upvotes: 45

Related Questions