jQuery selectors and backslashes

2019-02-23 16:50发布

问题:

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?

回答1:

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