Palmi Palmi - 7 months ago 25
Javascript Question

Jquery get element not working when id contains comma

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!');
}
});

Answer

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: \\