如果使用 querySelector 的话,传入的 selector 如果为数字的 class 或者 id 时会报错。但是使用 getElementById 以及 getElementByClass 则不会。

这个是因为跟 CSS 的转义有关。

It is valid, but requires some special handling. From here: http://mathiasbynens.be/notes/css-escapes

Leading digits

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 1 .

Basically, to escape any numeric character, just prefix it with  and append a space character ( ). Yay Unicode!

So your code would end up as (CSS first, JS second):

#\\31  {
    background: hotpink;
}

document.getElementById('1');
document.querySelector('#\\\\31 ');

Using querySelector with IDs that are numbers