Categories
JavaScript Answers

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

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *