0

I am working on feature where I have to use JS to highlight what is being selected by customer, however the variable in itself contains period as part of it. I have following code in the HTML and JS

HTML

<div id="div_product-size-icon-50174TV07.0" class="coin ">
   <div class="size"> 7</div>
</div>

JS

console.log('#'+'div_product-size-icon-'+productCode );
$('#'+'div_product-size-icon-'+productCode).addClass('active');

Where productCode is 50174TV07.0. This code is working fine if product code does not contain . as part of it, however in case product code have ., my code is not working.

I can not change product code as this is predefined so only option left for me is to modify my JS code to handle this.

Is there any other way apart from change . to _ in my HTML and work with it. My other biggest constraint is about the HTML as this is not directly controlled by me and this leave me with very limited choices.

Umesh Awasthi
  • 23,407
  • 37
  • 132
  • 204
  • I think [dgvid](http://stackoverflow.com/questions/70579/what-are-valid-values-for-the-id-attribute-in-html#answer-79022) has the answer. "You can select that element in CSS as `#first\.name` and in jQuery like so: `$('#first\\.name')`." – turbopipp Mar 04 '16 at 23:05

1 Answers1

4

You have to escape special characters with \\ per jQuery selector docs

Try :

productCode = productCode.replace('.','\\.');
$('#'+'div_product-size-icon-'+productCode).addClass('active');
charlietfl
  • 170,828
  • 13
  • 121
  • 150