Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get value of dom element whose id having dot and dollar sign

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.

like image 887
Shekhar Khairnar Avatar asked Dec 14 '22 06:12

Shekhar Khairnar


2 Answers

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>
like image 128
jcubic Avatar answered Dec 21 '22 10:12

jcubic


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>
like image 41
Ali Mamedov Avatar answered Dec 21 '22 09:12

Ali Mamedov