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
3 Answers
Reset to default 6This 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
版权声明:本文标题:javascript - How to select an element having a backslash in its id attribute - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744598450a2614919.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论