Jquery Syntax error, unrecognized expression on id selector - javascript

Im using angular and jquery to scroll to an element base on his location hash string.
In my situation i need to include in the string the '?' char, but its seems like jquery has problem with this.
This is the link:
when Are Lottery Results Updated OnThe Site
This is the jquery code:
var elem = '#' + $location.hash();
console.log($(elem));
The error:
Error: Syntax error, unrecognized expression: #whenAreLotteryResultsUpdatedOnTheSite?
Any solution?

Yes, jQuery will refuse to select elements with special characters in CSS selector. You just need to escape them with \\:
var elem = $location.hash().replace(/\?/, '\\\\?');
This will properly escape ? character.
Also note that location.hash will already include leading # so you don't need to prepend one more.

Related

Jquery Syntax error, unrecognized expression on attribute selector

I have html div with one attribute.
div exp_attribute="{"prop_val_name":1}">mydiv</div>
I tried to trigger click on it via jQuery like
$('div[exp_attribute={"prop_val_name":1}]').click(); // not working
$('div[exp_attribute=\\{"prop_val_name":1\\}]').click(); // not working with escaping special chars
$('div[exp_attribute=\\{\\"prop_val_name\\":1\\}]').click(); // not working with escaping more special chars
but keep getting error
Error: Syntax error, unrecognized expression: div[exp_attribute=\{\"prop_val_name\":1\}]
so any idea how to handle the issue?
Better to escape everything
$('div[exp_attribute=\\{\\"prop_val_name\\"\\:1\\}]').click();

Trying to escape a string to use as a jQuery selector

I have the following code, which I stole from another SO question,
$('#'+'^`test'.replace(/[!"#$%&'()*+,.\/:;<=>?#[\\\]^`{|}~]/g, "\\\\$&"))
which produces the following error.
Uncaught Error: Syntax error, unrecognized expression: #\\^\\`test(…)
I just have some IDs with crazy characters, like ^ and `, that I need jQuery to not choke on. I don't get why that error is happening, because if I manually add the slashes into the string like,
$('#'+'\\^\\`test')
then it works fine. What's wrong with the regex method?
I just have some IDs with crazy characters, like ^ and `, that I need jQuery to not choke on.
By far the simplest way to address that is with an attribute selector:
$('[id="' + theId + '"]').doSomething();
As long as theId doesn't contain backslashes or double quotes, no need for further escaping.
Another work around is to use the vanilla getElementById, which doesn't parse the selector. That way you still have the efficiency of selecting by id:
let res = $(document.getElementById('^`test'));
How about using this?
const $ID = function(selector){
return $('[id="' + selector.match(/#?(\S+)/)[1] + '"]')
}
Then you can use it just like jquery
$ID('#^`div')
You need 2 times the escape . Becouse first the replace/regex need the escape to write a escape. The next escape is need from jquery by $().
More clear syntax as the postet regex is:
"#^bla`".replace('^','\\\^').replace('`','\\\`');
will replace "#^bla`" to "#\\^bla\\`".
Uncaught Error: Syntax error, unrecognized expression: #\\^\\`test(…)
If you want to use your regex you must also escape [ ] with \[ and \].
"+".replace(/[!"#$%&'()*+,.'()*+,.\/:;<=>?#\[\\\]^`{|}~]/g, "yes")

Unrecognised expression with error for ids starting with an integer

I'm trying to grab an element from a page which has an id starting with an integer.
$('#3|assets_main|ast_module|start-iso-date')
I get the following error
Uncaught Error: Syntax error, unrecognized expression: |assets_main|ast_module|start-iso-date
I am using jQuery 1.7.1, I understand that the id in general is poorly named but is there any reason why jQuery will has issues with ids that start with integers?
In HTML5 the id can start with a numerical value, so your id is valid.
The issue is the pipe (|) characters in the selector; you need to escape them using \\:
$('#3\\|assets_main\\|ast_module\\|start-iso-date')
Working example

Why can't jQuery 3 identify the '#' character in an attribute selector?

I just tried switching my application to jQuery 3. I was going through some testing and everything was working as expected, until I came to a piece of my application that used a '#' symbol in a selector. I have a piece of jQuery that looks like this:
var $existingFilter = $container.find('.filterFeedItem[data-component-type=#somefilter]');
Using jQuery 3 I get an error:
jquery-3.0.0.js:1529 Uncaught Error: Syntax error,
unrecognized expression: .filterFeedItem[data-component-type=#somefilter]
Does anyone know why jQuery can no longer parse selectors containing this symbol?
Note, the change apparently took place at version 2.0, as version 2.1.3 returned element using selector
var $existingFilter1 = $container.find('.filterFeedItem[data-component-type=#somefilter]');
jsfiddle https://jsfiddle.net/f8nej922/2/
Though have not been able to locate specific reference to or description of change at jQuery 2.2 and 1.12 Released documentation.
As noted by #BoltClock, change is related to Selector: Remove "#" exception for identifier tokens.
You can esacape # character with \\; quote value at attribute selector; or use $.escapeSelector()
var $existingFilter = $container
.find('.filterFeedItem[data-component-type=\\#somefilter]');
var $existingFilter = $container
.find('.filterFeedItem[data-component-type="#somefilter"]');
var $existingFilter = $container
.find('.filterFeedItem[data-component-type='
+ $.escapeSelector('#somefilter') + ']');
jsfiddle https://jsfiddle.net/f8nej922/4/
By jQuery's documentation, the attribute value:
Can be either a valid identifier or a quoted string.
The valid identifier being any valid css identifier:
https://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
In CSS, identifiers (including element names, classes, and IDs in
selectors) can contain only the characters [a-zA-Z0-9] and ISO 10646
characters U+00A0 and higher, plus the hyphen (-) and the underscore
(_); they cannot start with a digit, two hyphens, or a hyphen followed
by a digit. Identifiers can also contain escaped characters and any
ISO 10646 character as a numeric code (see next item). For instance,
the identifier "B&W?" may be written as "B\&W\?" or "B\26 W\3F".
Since you are wanting to use #, you need to escape or quote the value:
//Note the quotes v --------- v
.find('.filterFeedItem[data-component-type="#somefilter"]');

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"
try
console.log($("#"+d));
your solution is passing the double quotes as part of the string.
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 */ }
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.
Try using:
console.log($("#"+d));
This will remove the extra quotes you were using.
Try this (ES5)
console.log($("#" + d));
ES6
console.log($(`#${d}`));
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 it was so I could troubleshoot and fix it.
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);
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?
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)+"')";

Categories