开发者

jQuery selectors and backslashes

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

<div id="domain\element\div">My Div</di开发者_开发知识库v>

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?


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜