-1

JQuery 3.2.1 is throwing following error

jquery-3.2.1.min.js:2 Uncaught Error: Syntax error, unrecognized expression: #row_L&TFH
    at Function.ga.error (jquery-3.2.1.min.js:2)
    at ga.tokenize (jquery-3.2.1.min.js:2)
    at ga.select (jquery-3.2.1.min.js:2)
    at Function.ga [as find] (jquery-3.2.1.min.js:2)
    at r.fn.init.find (jquery-3.2.1.min.js:2)
    at new r.fn.init (jquery-3.2.1.min.js:2)
    at r (jquery-3.2.1.min.js:2)
    at Object.success (allocate.js:84)
    at i (jquery-3.2.1.min.js:2)
    at Object.fireWith [as resolveWith] (jquery-3.2.1.min.js:2)

on following line of code

$('#row_'+code).remove();

when code has "&" in it throws error. for ex: code = "L&TFH" it throws error but when code = "ABB" it doesn't.

Lokesh Agrawal
  • 3,269
  • 6
  • 28
  • 66
  • & is allowed in a id ? can you check that – Panther Sep 29 '19 at 17:55
  • https://stackoverflow.com/questions/70579/what-are-valid-values-for-the-id-attribute-in-html – Panther Sep 29 '19 at 17:55
  • @Panther an id can contain any non-whitespace character – Pointy Sep 29 '19 at 17:57
  • google https://www.kevinleary.net/jquery-syntax-error-unrecognized-expression/ – xdeepakv Sep 29 '19 at 17:58
  • @xdeepakv that article is pretty much useless. There's nothing wrong with this question; I don't understand why it's being downvoted. – Pointy Sep 29 '19 at 18:05
  • And that jquery article specifically mentions, if IDs are not in the correct format it throw an exception. I think that is . not useless at all. – xdeepakv Sep 29 '19 at 18:12
  • @xdeepakv it does absolutely nothing to help the OP solve the problem. Note, in point of fact, that I've already provided an answer that **does** solve the problem. – Pointy Sep 29 '19 at 18:12
  • i m not the only one downvote bro. Plz check. article correctly. "is an invalid selector expression." – xdeepakv Sep 29 '19 at 18:15
  • @xdeepakv yes, it's an invalid selector expression, but it can be made valid with a very simple change. Everybody who posts a question here has something wrong with their code; that's the whole point. – Pointy Sep 29 '19 at 18:15

1 Answers1

1

When an id value isn't an "identifier", you have to quote the characters that don't fit with that syntax. Thus "#row_L&TFH" won't work but "#row_L\\&TFH" will.

You can achieve that with

$('#row_' + code.replace(/[^0-9A-Za-z_]/g, "\\$0")).remove();

That applies not only to id values but also to class names. It's not invalid for an id or a class name to contain non-identifier characters, but you're forced to use explicit notation in the CSS selector to reference them. It's analogous to the fact that in JavaScript an object property name can be any string, but unless it's an identifier you have to use [ ] notation with a string to access or set the property value.

Pointy
  • 371,531
  • 55
  • 528
  • 584