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.
It is valid, but requires some special handling. From here: http://mathiasbynens.be/notes/css-escapes
So your code would end up as (CSS first, JS second):
I needed an approach which was automated. A recent change meant the id values used were no longer simple alphabetic characters and included numbers and special characters.
I ended up using
CSS.escape
: https://developer.mozilla.org/en-US/docs/Web/API/CSS/escapeFirst, this is the failing case:
And now using
CSS.escape
:See how it correctly changes to show
After
, demonstrating the selector worked!Because while they are valid in the HTML5 spec, they are not valid in CSS, which is what "query selector" means.
Instead, you would have to do this:
document.querySelector("[id='1']")
, which is very long-winded considering you could give it a meaningful ID likemessage1
or something ;)