1

we have some legacy code where Html element ID's are populated dynamically from database data (I cant change the data here) ex. <input type="text" id="2314/test/film/code\branch"/>

when I get the ID from click event like below var src = window.event.srcElement; I get src.id= "2314/test/film/code\\branch";

I want to use the src.id to find the same element in different function like $(_element).find("[id='" + src.id + "']").get();

which is failing to get any ID since I see "\" is replaced with "\\"

Please suggest me how to get around this ?

lmgonzalves
  • 6,518
  • 3
  • 22
  • 41
Grasshopper
  • 1,778
  • 6
  • 27
  • 48

3 Answers3

1

I don't think jQuery lets you use / in a selector. It is an illegal character in an id name, but still odd that jquery seems to flat out refuse it. Since JS has no problem with that selector You can select it with JS then pass it off to the jquery wrapper.

$(document.getElementById('2314/test/film/code\\branch'));
chiliNUT
  • 18,989
  • 14
  • 66
  • 106
  • 1
    Each \ has to be escaped, the final string must have 2 \, i.e. `'2314/test/film/code\\\\branch'` – Musa Jun 01 '15 at 19:56
  • @Musa in jquery, yes that is true, but `getElementById` does not have that same requirement (since it is native JS), so my code should work fine as written – chiliNUT Jun 01 '15 at 19:57
  • The original ID in the HTML only has one backslash, so I believe @chiliNUT is correct. – Matt Browne Jun 01 '15 at 19:58
  • @Musa oh I see, I thought you were saying it needed to be double escaped. Then yeah, what Matt Browne said. – chiliNUT Jun 01 '15 at 19:59
  • if you're using getElementById then you don't need to escape the \ at all, just use one \ – Musa Jun 01 '15 at 19:59
  • @Musa nope, if it was 'code\branch' it would look for whatever the escape sequence '\b' is, so you still need the double backslash – chiliNUT Jun 01 '15 at 20:00
0

Maybe it´s works for you

http://codepen.io/luarmr/pen/vOgoLO

$("[id='" + str.replace(/\\/g,'\\\\')  + "']").html(str)
Raúl Martín
  • 4,471
  • 3
  • 23
  • 42
-1

The correct regex for backslash is '\\\\'.

omikes
  • 8,064
  • 8
  • 37
  • 50