jQuery: Uncaught Error: Syntax error, unrecognized expression - javascript

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)+"')";

Related

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")

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 eq function unexpected behavior

I found a bug in a program I had written, but the behavior of the error is inexplicable to me:
If I have:
<input type="text" name="cust_id" value="666" />
<input type="text" name="phone[]" value="666" />
And then use this selector:
var test = $("input[name=phone[]]:eq(0)");
test.css("color", "red");
I see this:
What I'm surprised by is the fact that the eq(0) selects the first input even though I explicitly tell it to find only ones with name=phone[]
Here is a fiddle: https://jsfiddle.net/1xdnv1t8/
Is this expected behavior? Does the eq selector ignore attribute selectors?
You need to quote name attribute:
var test = $("input[name='phone[]']:eq(0)");
because phone[] is not valid name without quotes. So jQuery parser (or DOM) simply ignores everything invalid and treats selector as if it was simply input[name='phone']:eq(0). Also worth noting, that looks like this behaviour is fixed in more up to date versions of jQuery. You use pretty old 1.6.4 in your demo, but if you check it with 1.8.x and above it will work properly throwing error.
For example, if you try
try {
document.querySelector("input[name=phone[]]")
}
catch(e) {
alert(e.message)
}
it will even throw an error
Uncaught SyntaxError: Failed to execute 'querySelector' on 'Document': 'input[name=phone[]]' is not a valid selector.
But jQuery is more forgiving and it just selects whatever it can.
Use
var test = $("input[name='phone[]']:eq(0)");
JSFiddle
In the selector especification states
jQuery( "[attribute='value']" )
attribute: An attribute name.
value: An attribute value. Can be either an unquoted single word or a quoted string.
You are missing quotes around the attribute value. Try this -
var test = $('input[name="phone[]"]:eq(0)');
The square brackets in your selector confuse the attribute selection part as it is not quoted. Notice if you change the name of the second input to phone then it works as expected:
$("input[name=phone]:eq(0)")
Alternatively, wrap the attribute selector in quotes:
$("input[name='phone']:eq(0)")
While quoting the name attribute's value isn't strictly required (jQuery for the most part will work fine without them), as you noticed you can run into unusual situations when there are non-alphanumeric characters involved and jQuery interprets them as CSS notation.
The solution is to always properly escape any of these characters (:, ., [, ], etc.) as jQuery recommends, with two backslashes:
In order to tell jQuery to treat these characters literally rather
than as CSS notation, they must be "escaped" by placing two
backslashes in front of them.
So according to the jQuery documentation, you should be using var test = $("input[name='phone\\[\\]']:eq(0)"); as the selector (although simply properly quoting the string in your case will also work fine).
jsFiddle example
Ref: How do I select an element by an ID that has characters used in CSS notation?

Jquery Syntax error, unrecognized expression on id selector

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.

JavaScript/jQuery removing character 160 from a node's text() value - Regex

$('#customerAddress').text().replace(/\xA0/,"").replace(/\s+/," ");
Going after the value in a span (id=customerAddress) and I'd like to reduce all sections of whitespace to a single whitespace. The /\s+/ whould work except this app gets some character 160's between street address and state/zip
What is a better way to write this? this does not currently work.
UPDATE:
I have figured out that
$('.customerAddress').text().replace(/\s+/g," ");
clears the 160s and the spaces.
But how would I write a regex to just go after the 160s?
$('.customerAddress').text().replace(String.fromCharCode(160)," ");
didn't even work.
Note: I'm testing in Firefox / Firebug
Regarding just replacing char 160, you forgot to make a global regex, so you are only replacing the first match. Try this:
$('.customerAddress').text()
.replace(new RegExp(String.fromCharCode(160),"g")," ");
Or even simpler, use your Hex example in your question with the global flag
$('.customerAddress').text().replace(/\xA0/g," ");
\s does already contain the character U+00A0:
[\t\n\v\f\r \u00a0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000]
But you should add the g modifier to replace globally:
$('#customerAddress').text().replace(/\s+/g, " ")
Otherwise only the first match will be replaced.
Sorry if I'm being obvious (or wrong), but doesn't .text() when called w/o parameters just RETURNS the text? I mean, I don't know if you included the full code or just an excerpt, but to really replace the span you should do it like:
var t = $('#customerAddress').text().replace(/\xA0/,"").replace(/\s+/," ");
$('#customerAddress').text(t);
Other than that, the regex for collapsing the spaces seems OK, I'm just not sure about the syntax of your non-printable char there.

Categories