views:

149

answers:

3

I have some elements with (.) periods in them and I need to select them but I need some escape characters to do so I believe. How can I sure that my string that may have a period in it will be escaped properly. Something like this I guess?

var title = "User1.Title";
var string = //replace any periods with escape sequence?
$('#'+string).show();

It may have more than one (.) period, hopefully not but if I can replace all (.) periods so I can do my selection that would be great.

+4  A: 

Do you mean this?

$('#'+string.replace(".", "\\.")).show();
Gumbo
A: 

This works:

$("[id="+string+"]").show()

no need to escape it if you explicitly specify that it's an ID

duckyflip
+2  A: 

You could do this...

$("[id="+string+"]").show();

...but the problem with this guy is that is not that fast since it will traverse the entire DOM tree looking for every guy with that id, not only one.

You could also do this...

$('#'+string.replace(".", "\\.")).show();

.. that jQuery will pre-parse that selector and use document.getElementById behind the scenes.

You could also do this

$(document.getElementById(string)).show();

... wich yelds the same effect and you don't have to worry about CSS special characters. Just be careful with IE(6 and 7) and Opera wich selects elements not only by it's ID but also by it's name.

Pablo Cabrera