0

I have a jQuery variable that I wanna use as the selector. The variable contains colon, ':', as seen in the example below.

var testVariable = text1:text2:4882746225

The variable id used as the id of a div element and I cannot remove the colons. There is another div element inside the parent div. Below you can see how it looks.

<div id="text1:text2:4882746225">

<div class="inner">
Sample content
</div>

</div>

What I want to do is to select the inner div element, which has the class inner, via the parent div's id. I have tried the following but it didn't work.

$('#'+testVariable+' .inner')

Does anyone else have run into a similar problem? If so, what is the solution? What am I doing wrong here?

Thanks in advance.

Metin
  • 99
  • 1
  • 2
  • 11

1 Answers1

2

You need to escape those special characters with a double backslash \\.

var testVariable = "text1\\:text2\\:4882746225";

update (in response to comment):

But you can access it at some point right? Well then we have to work a little harder and punch the duck for as long as we need. Like

var newSelector = $('div').attr('id').replace(/:/g, '\\\\:');

and then use newSelector to select

$(newSelector);
jAndy
  • 231,737
  • 57
  • 305
  • 359
  • Hey jAndy, I forgot to state that I am not allowed to edit the variable. Have to use it as it is. Just edited the question. – Metin Mar 22 '12 at 11:56