问题描述
根据我的理解,HTML5规范允许您使用这种数字的ID。
From what I understand the HTML5 spec lets you use IDs that are numbers like this.
<div id="1"></div>
<div id="2"></div>
我可以使用 getElementById
不是用 querySelector
。如果我尝试执行以下操作,在控制台中获取 SyntaxError:DOM Exception 12 。
I can access these fine using getElementById
but not with querySelector
. If I try do the following I get SyntaxError: DOM Exception 12 in the console.
document.querySelector("#1")
我只是想知道为什么使用数字作为ID不起作用 querySelector
,当HTML5规范说这些都是有效的。我尝试多个浏览器。
I'm just curious why using numbers as IDs does not work querySelector
when the HTML5 spec says these are valid. I tried multiple browsers.
推荐答案
它是有效的,但需要一些特殊的处理。从这里开始:
It is valid, but requires some special handling. From here: http://mathiasbynens.be/notes/css-escapes
如果标识符的第一个字符是数字,则需要根据Unicode代码点。例如,字符1的代码点是U + 0031,因此您可以将其转义为\000031或\31。
If the first character of an identifier is numeric, you’ll need to escape it based on its Unicode code point. For example, the code point for the character 1 is U+0031, so you would escape it as \000031 or \31 .
基本上,字符,只是前缀为\3并附加一个空格字符()。 Yay Unicode!
Basically, to escape any numeric character, just prefix it with \3 and append a space character ( ). Yay Unicode!
因此,您的代码最终将是(CSS first,JS second):
So your code would end up as (CSS first, JS second):
#\31 {
background: hotpink;
}
document.getElementById('1');
document.querySelector('#\\31 ');
这篇关于使用ID为number的querySelector的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!