Using querySelector with IDs that are numbers(使用带有数字 ID 的 querySelector)
问题描述
据我了解,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.
推荐答案
有效,但需要一些特殊处理.从这里开始:http://mathiasbynens.be/notes/css-escapes
It is valid, but requires some special handling. From here: http://mathiasbynens.be/notes/css-escapes
前导数字
如果标识符的第一个字符是数字,则需要根据其 Unicode 代码点对其进行转义.例如,字符 1 的代码点是 U+0031,因此您可以将其转义为 00031 或 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 00031 or 31 .
基本上,要转义任何数字字符,只需在其前面加上 3 并附加一个空格字符 ( ).耶 Unicode!
Basically, to escape any numeric character, just prefix it with 3 and append a space character ( ). Yay Unicode!
所以你的代码最终会是(CSS第一,JS第二):
So your code would end up as (CSS first, JS second):
#31 {
background: hotpink;
}
document.getElementById('1');
document.querySelector('#\31 ');
这篇关于使用带有数字 ID 的 querySelector的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用带有数字 ID 的 querySelector


- 失败的 Canvas 360 jquery 插件 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- 400或500级别的HTTP响应 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- addEventListener 在 IE 11 中不起作用 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- Fetch API 如何获取响应体? 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06