querySelector 与 getElementById 获取元素的区别:CSS 标识符规范限制

作者:像素漫游时间:2026-10-26 18:30:15浏览:367

本文通过实际案例对比 querySelector 与 getElementById 的行为差异。当元素 ID 以数字开头时,querySelector 会因违反 CSS 标识符规范而报错,无法获取元素;而 getElementById 不受此限制,可正常获取。理解这一区别有助于避免前端开发中的常见陷阱。

querySelector 与 getElementById 获取元素的区别

这是由新浪同事 xiaoniu 发现的一个现象,具体表现如下。


<!DOCTYPE html> 
<html> 
<head> 
<meta charset="utf-8"/> 
</head> 
<body> 
<div id="02E503E2A1C011CFC85B7B701A0677EC0900000000000001"></div> 
<script> 
var str = '02E503E2A1C011CFC85B7B701A0677EC0900000000000001'; 
function bySelector(id) { 
return document.querySelector('#'+id); 
} 
function byId(id) { 
return document.getElementById(id); 
} 

alert(bySelector(str)); 
alert(byId(str)); 
</script> 
</body> 
</html> 

以数字开头的 ID 获取差异

我们定义了两个函数 bySelector 和 byId,分别使用 querySelector 和 getElementById 方法来获取页面元素。页面中存在一个 id 为“02E503E2A1C011CFC85B7B701A0677EC0900000000000001”的 div 元素。测试结果显示,在所有支持 querySelector 的浏览器中,通过 bySelector 方法获取该元素均会报错,无法成功获取;然而,通过 getElementById 方法却能正常获取到该元素。起初怀疑是因为 ID 字符串过长导致 querySelector 失效,但经过排查发现,真正的原因在于 querySelector 遵循 CSS 规范,而 CSS 标识符不允许以数字开头。

CSS 标识符规范限制

W3 写道 In CSS, identifiers (including element names, classes, and IDs in selectors) can contain only the characters [a-zA-Z0-9] and ISO 10646 characters U+00A0 and higher, plus the hyphen (-) and the underscore (_); they cannot start with a digit, two hyphens, or a hyphen followed by a digit. Identifiers can also contain escaped characters and any ISO 10646 character as a numeric code (see next item). For instance, the identifier "B&W?" may be written as "B\&W\?" or "B\26 W\3F".

作者最新文章