使用带有数字 ID 的 querySelector [英] Using querySelector with IDs that are numbers

查看:22
本文介绍了使用带有数字 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆