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.
Just escape the characters:
var foo = 'XS_19MAY2016_012720_311.04$'; $('#' + foo.replace(/[.$]/g, '\\\\$&') + '_cal').text('foo')
<script src="https://ajax.googleapis.com/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.com/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 compatibility, 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.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div id="XS_19MAY2016_012720_311.04$_cal"> hello </div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.