JQuery search by ID if ID has a quotation mark

83 views Asked by At

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

There are 2 answers

4
Chris Barr On

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:

Technically, the value for an id attribute may contain any character, except whitespace characters. However, to avoid inadvertent errors, only ASCII letters, digits, '_', and '-' should be used, and the value for an id attribute should start with a letter.

1
qrsngky On

The replacement certainly works (for example in jQuery 1.12.4):

c = "Bel'Veth"
c = c.replace("'", "\\'")
$("#"+c).addClass("selected");
.selected{
  font-weight: bold; 
  color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

<span id="Bel'Veth">Your element</span>

The error message Syntax error, unrecognized expression: #Bel\\'Veth happens if you replace it twice:

try{
  c = "Bel'Veth"
  c = c.replace("'", "\\'")
  c = c.replace("'", "\\'")
  $("#"+c).addClass("selected");
}catch(e){
  console.log(e.message);
}
.selected{
  font-weight: bold; 
  color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

<span id="Bel'Veth">Your element</span>

That said, it should be easier to just avoid using such values for ids.