My Div<...">

JQuery selectors and backslash

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

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

It seems impossible to get jQuery to select an item by id. Here is 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 console output displays the first two as empty while the third is working;

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

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

+4
source share
1 answer

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

If you can't change the HTML, jQuery can work with backslashes in identifiers and identifiers. In addition, you will need to use four backslashes to match each literal backslash in your identifier selector:

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

You achieve this

  • ID capture:

     domain\element\div 
  • Adding the # character and escaping backslashes for the selector:

     #domain\\element\\div 
  • Escaping each pair of backslashes for use in JavaScript strings by doubling them (also note the quotation marks):

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

jsFiddle

+16
source

All Articles