admin管理员组

文章数量:1394137

While going through official doc ,I am unable to understand that for matching the first div ,how they have written four backslash(\) ,In my opinion there should be two backslash.I am unable to find the valid logic for this reason

 <div id="foo\bar"></div>
 <div id="foo:bar"></div>
 document.querySelector('#foo\\\\bar');  // It matches the first div

While going through official doc ,I am unable to understand that for matching the first div ,how they have written four backslash(\) ,In my opinion there should be two backslash.I am unable to find the valid logic for this reason

 <div id="foo\bar"></div>
 <div id="foo:bar"></div>
 document.querySelector('#foo\\\\bar');  // It matches the first div
Share Improve this question edited Feb 22, 2018 at 7:05 Danny asked Feb 21, 2018 at 10:28 DannyDanny 19312 bronze badges 2
  • Have you tested the code with 1, 2, 3, and 4 back-slashes? I think you'll find out why eventually. Also, that's a horrible way of identifying elements. – Andy Commented Feb 21, 2018 at 10:32
  • One each to escape slash ` and escaper slash ` – gurvinder372 Commented Feb 21, 2018 at 10:33
Add a ment  | 

3 Answers 3

Reset to default 6

This is due to the browser escapes the backslash in the id attribute. So it will bee

<div id="foo\\bar"></div>

So inorder to select the element we need to provide \\\\ to select the element.

var elements = document.querySelector('#foo\\\\bar');
console.log(elements);
var elements = document.querySelector('#foo\\bar');
console.log(elements);
<div id="foo\bar"></div>
<div id="foo:bar"></div>

Update based on ment You can read more information regarding this in following links:-

https://mathiasbynens.be/notes/css-escapes

https://www.w3/TR/CSS21/syndata.html#characters

You have two double backslashes. As you know, the backslashe is a "escape" character.

So your selector string bee:

#foo\\bar <--- to have this string in a variable, you need to use '#foo\\\\bar'

Now, the double backslash that left (in the string) will be used (again as a escape character) by the querySelector.

You can checkout more details about how selectors can be written here.

It's encoding rules to put diffrence with some special characters. The '\b' is a bination of charactere that mean backspace so if you don't want to mean it you have to write '\\b', the second step that you have to encode '\' on your string so to cover this case you have to write '\\'. So for that your output must be "foo\\\\bar"

本文标签: javascriptHow to select an element having a backslash in its id attributeStack Overflow