1

I have these class with "+" string for eg. crg-th-post-gsm+bb-sub-sub-all-programs but the problem is when I try to $('.crg-th-post-gsm+bb-sub-sub-all-programs') jquery can't seem to find it because of the '+' I tried testing it without the "+" it works fine. How can I make it work with "+"? is there a way?

another workaround I can also think is replace the string "+" using .replace but when I use the string.replace(/+/g,'-') it does not recognize.

Vian Ojeda Garcia
  • 827
  • 4
  • 17
  • 34
  • Just a note. You can have multiple classes. like class='class1 class2'. So if the + is to represent that you have more than 1 classes it might not be necessary. – Word Rearranger Jan 23 '19 at 03:27
  • Have a look at this, it might help your understanding https://www.w3schools.com/jquery/jquery_ref_selectors.asp – sjdm Jan 23 '19 at 03:28
  • The reason this is an issue is because `+` has a meaning for a selector, see: https://stackoverflow.com/questions/1139763/what-does-the-plus-sign-css-selector-mean – Evan Trimboli Jan 23 '19 at 03:30
  • I would highly suggest changing your class name, otherwise you'll have to escape that class *everywhere*. Why put yourself through that? – Tyler Roper Jan 23 '19 at 03:31
  • @TylerRoper it comes from data retrieved from users so I can't remotely change that. I expect there will be instance like this so I don't want to handle this by changing the class. Another option may be replacing all the possible "+" – Vian Ojeda Garcia Jan 23 '19 at 04:01

2 Answers2

3

Use escapeSelector doc:

console.log($('.' + $.escapeSelector("crg-th-post-gsm+bb-sub-sub-all-programs" )).text());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="crg-th-post-gsm+bb-sub-sub-all-programs">TEXT</div>
quirimmo
  • 9,800
  • 3
  • 30
  • 45
1

You need to escape the + with \\

$('.crg-th-post-gsm\\+bb-sub-sub-all-programs').text( 'Hello there' );
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="crg-th-post-gsm+bb-sub-sub-all-programs"></div>
Thum Choon Tat
  • 3,084
  • 1
  • 22
  • 24