Categories
JavaScript Answers

How to Use querySelector with IDs that are Numbers in JavaScript?

Spread the love

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.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.