0

I have a variable that I want to use in a selector but the variable contains special characters. Is there a way to do this?

hasSpecialChr='dynamicVar[1][3]';

element = $('li.parent#'+hasSpecialChr);

Edit: Answered in first comment below.

Phil
  • 2,176
  • 10
  • 33
  • 56
  • 3
    Quick google search of your question : https://learn.jquery.com/using-jquery-core/faq/how-do-i-select-an-element-by-an-id-that-has-characters-used-in-css-notation/ – Karl-André Gagnon Aug 24 '16 at 14:57
  • embarrassment ensues... – Phil Aug 24 '16 at 15:00
  • 1
    possible duplicate of: http://stackoverflow.com/questions/739695/jquery-selector-value-escaping – JonSG Aug 24 '16 at 15:06
  • 1
    @Phil It happens to everyone :P Just has to be careful! – Karl-André Gagnon Aug 24 '16 at 15:08
  • As stated by @Karl-André Gagnon The answer is to use a function to strip out the characters as described by JQuery docs https://learn.jquery.com/using-jquery-core/faq/how-do-i-select-an-element-by-an-id-that-has-characters-used-in-css-notation/ – Phil Aug 24 '16 at 16:14

2 Answers2

0

Try this:

hasSpecialChr='dynamicVar\\[1\\]\\[3\\]';
element = $('li.parent#'+hasSpecialChr);
0

This may solve your problem:

s.replace(/[^a-z\d\s]+/gi, "");

removes all except letters, numbers and white space.

hasSpecialChr='dynamicVar[1][3]';
hasSpecialChr.replace(/[^a-z\d\s]+/gi, "");
element = $('li.parent#'+hasSpecialChr);
Mohan Dere
  • 4,497
  • 1
  • 25
  • 21