Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery get element not working when id contains comma

Tags:

jquery

Why does the jquery selector not work when the id contains a comma? See http://jsfiddle.net/sGQas/188/

<div id="1,3">Hello There!</div>

$(document).ready(function () {
  var str = "#1,3";

  if ($(str).length) {
    alert($(str).position().left);
  } else {
    alert('The element "'+str+'" does not exist on the document!');
  }
});
like image 202
Palmi Avatar asked Dec 06 '25 07:12

Palmi


1 Answers

You need to escape the comma with two backslashes:

var str = "#1\\,3";

jsFiddle example

See https://learn.jquery.com/using-jquery-core/faq/how-do-i-select-an-element-by-an-id-that-has-characters-used-in-css-notation/ and https://api.jquery.com/category/selectors/

To use any of the meta-characters ( such as !"#$%&'()*+,./:;<=>?@[\]^{|}~ ) as a literal part of a name, it must be escaped with with two backslashes: \\

like image 196
j08691 Avatar answered Dec 08 '25 21:12

j08691