SoFunction
Updated on 2025-03-01

js querySelector and getElementById get element through id

This was discovered by Sina colleague Xiaoniu, as follows

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

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

The two functions bySelector and byId get elements through querySelector and getElementById respectively.

There is an element on the page with the id "02E503E2A1C011CFC85B7B701A0677EC0900000000000000000000000000001".

Result: All browsers that support querySelector cannot be obtained through bySelector (an error report), but can be obtained through getElementById.

I started to suspect that the id string was too long, which caused the querySelector to not be able to get it. The real reason is that querySelector is implemented according to the css specification, that is, the css identifier cannot start with a number.

W3 wrote
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".