6

I have a dom element that contains a fully qualified name as part of the id attribute;

<div id="domain\element\div">My Div</div>

It seems impossible to get jQuery to select the element by ID. Here's my experiment;

var $e1 = $('#domain\\\element\\\div');
var $e2 = $('#domain\\element\\div');
var $e3 = $(document.getElementById('domain\\\element\\\div'));
console.log($e1);
console.log($e2);
console.log($e3);

The output of the console displays the first two as empty while the third works;

[]
[]
<div id=​"domain\element\div">​TODO write content​</div>​

I am using jQuery 1.5.2. Is this a bug with jQuery itself or are my selector strings wrong?

Kevin
  • 948
  • 2
  • 11
  • 19
  • 6
    The backslash isn't a valid character in an ID. – BoltClock Apr 28 '11 at 22:58
  • 2
    For the non-believers: http://stackoverflow.com/questions/70579/what-are-valid-values-for-the-id-attribute-in-html – sdleihssirhc Apr 28 '11 at 23:02
  • Hmm, that is interesting. As a couple people have mentioned, those aren't valid id's. Is it a reasonable thing to try to change them from \ to _ or - ? Or is this just more of a curiosity thing? – ataddeini Apr 28 '11 at 23:16
  • If backslashes are invalid characters for ID, then why does the html validate correctly whenusing ? – Kevin Apr 29 '11 at 09:35

1 Answers1

19

If you can change the ID within your HTML code, find some other separator than a backslash \ for your ID so that you can make a valid ID for your selector (see here). An underscore _ would be good.

If you can't alter the HTML, jQuery can still work with backslashes in IDs and ID selectors. Except, you'll need to use four backslashes to match each literal backslash in your ID selector:

$('#domain\\\\element\\\\div')

You achieve this by

  1. Taking the ID:

    domain\element\div
    
  2. Adding the # symbol and escaping the backslashes for the selector:

    #domain\\element\\div
    
  3. Escaping each pair of backslashes for use in JavaScript strings by doubling them (also notice the quotes):

    '#domain\\\\element\\\\div'
    
  4. Then passing the string to $() as above.

jsFiddle

Community
  • 1
  • 1
BoltClock
  • 630,065
  • 150
  • 1,295
  • 1,284
  • Didn't understand #3. you already escaped them at #2. why again ? – Royi Namir Dec 04 '13 at 16:35
  • @Royi Namir: The ID has backslashes, so to use it in a selector you need to escape them, that's #2. Next, when you put it in a JavaScript string, you need to escape them a second time, hence #3. This is just a general rule of thumb. – BoltClock Dec 04 '13 at 16:36