I’m trying to look for a certain html element by its ID, which has a quotation mark in it. When the script looks for the element it throws this error:
Uncaught Error: Syntax error, unrecognized expression: #Bel’Veth
In advance, I can’t use another variable name.
Here’s my JavaScript code:
c = "Bel'Veth"
$("#"+c).addClass("selected");
My HTML:
<div id="Bel'Veth">Bel'veth</div>
I already tried using c = c.replace("'", "'")
and c = c.replace("'", "\'")
, it results in the following errors:
Uncaught Error: Syntax error, unrecognized expression: #Bel'Veth
Uncaught Error: Syntax error, unrecognized expression: #Bel\'Veth
2
Answers
ID’s cannot contain a quote character. So you will have to find a way to remove it from the ID whereever that is coming from, and then your code will work.
Read up on what is allowed and why here: https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/id
From that page it says:
The replacement certainly works (for example in jQuery 1.12.4):
The error message
Syntax error, unrecognized expression: #Bel\'Veth
happens if you replace it twice:That said, it should be easier to just avoid using such values for ids.