Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
90
rated 0 times [  92] [ 2]  / answers: 1 / hits: 156057  / 11 Years ago, sat, november 30, 2013, 12:00:00

From what I understand the HTML5 spec lets you use IDs that are numbers like this.



<div id=1></div>
<div id=2></div>


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)


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.


More From » html

 Answers
484

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



Basically, to escape any numeric character, just prefix it with 3 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 ');

[#73973] Friday, November 29, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ronaldo

Total Points: 694
Total Questions: 85
Total Answers: 103

Location: Somalia
Member since Mon, Feb 27, 2023
1 Year ago
;