Sometimes, we want to use querySelector
with IDs that are numbers in JavaScript.
In this article, we’ll look at how to use querySelector
with IDs that are numbers in JavaScript.
Use querySelector with IDs that are Numbers in JavaScript
To use querySelector
with IDs that are numbers in JavaScript, we have to escape the unicode code point representation of the number.
For instance, we can write:
<div id='1'>
hello world
</div>
Then we write:
const el = document.querySelector('#\\31');
console.log(el)
to select the div with ID 1.
U+0031
is the Unicode code point of the character 1, so we pass in \31
, which is the escaped version of the Unicode code point representation of 1.
el
should be the div with ID 1 as a result.
Conclusion
To use querySelector
with IDs that are numbers in JavaScript, we have to escape the unicode code point representation of the number.