I am facing problem with getting value of an element whose id
contains special character as .
and $
sign.
my id to element is "XS_19MAY2016_012720_311.04$_cal"
I am using syntax of jQuery as:
$("#"+xyz+"_cal").val() where xyz is variable having above id.
I am getting error as:
Error: Syntax error, unrecognized expression: #XS_19MAY2016_012720_311.04$_cal.
What I doing wrong or what I need to do to correct it.
I am facing problem with getting value of an element whose id
contains special character as .
and $
sign.
my id to element is "XS_19MAY2016_012720_311.04$_cal"
I am using syntax of jQuery as:
$("#"+xyz+"_cal").val() where xyz is variable having above id.
I am getting error as:
Error: Syntax error, unrecognized expression: #XS_19MAY2016_012720_311.04$_cal.
What I doing wrong or what I need to do to correct it.
Share Improve this question edited May 19, 2016 at 9:25 Ali Mamedov 5,2563 gold badges38 silver badges51 bronze badges asked May 19, 2016 at 8:34 Shekhar KhairnarShekhar Khairnar 2,6913 gold badges28 silver badges46 bronze badges 4- because of dot inside your id. we can get any element object via this $('.class'); or $('#id'). – Ranjeet Singh Commented May 19, 2016 at 8:37
-
use vanilla way
document.getElementById('')
– guradio Commented May 19, 2016 at 8:38 - I have checked it on my side by replacing id with var xyz = "XS_19MAY2016_012720_31104"; alert( $("#"+xyz+"_cal").val() ); <input id="XS_19MAY2016_012720_31104_cal" value="5"/> . it is working. – Ranjeet Singh Commented May 19, 2016 at 8:40
-
1
if its input this will work
$("input[id='XS_19MAY2016_012720_311.04$_cal']")
or replace with div depending on your element – Anupam Commented May 19, 2016 at 8:42
3 Answers
Reset to default 6Just escape the characters:
var foo = 'XS_19MAY2016_012720_311.04$';
$('#' + foo.replace(/[.$]/g, '\\$&') + '_cal').text('foo')
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="XS_19MAY2016_012720_311.04$_cal"></div>
You can use this way to do that (without symbol escaping).
$(function() {
var
id = "XS_19MAY2016_012720_311.04$_cal",
text;
text = $('[id="' + id +'"]').text();
alert(text);
});
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="XS_19MAY2016_012720_311.04$_cal">Yay!</div>
You need to tell jquery that string is absolutely an 'ID', not a class.
HTML ID attribute can't includes space, and must have at least one character. But for patibility, better to avoid '_', '.'
Here using the Javascript builtin method, and turn the DOM node to a Jquery object. It looks redundant, but it is steady and easy to read.
$(function() {
var xyz = 'XS_19MAY2016_012720_311.04$';
e = $(document.getElementById(xyz + '_cal'));
console.log(e.text());
});
<script src="https://ajax.googleapis./ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="XS_19MAY2016_012720_311.04$_cal">
hello
</div>