How to use querySelector with IDs that are numbers with CSS and JavaScript?

In HTML and CSS, IDs starting with a number are technically not valid. According to the HTML specification, ID tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens (“-”), underscores (“_”), colons (“:”), and periods (“.”).

However, modern browsers tend to be lenient and may allow IDs that start with a number, but it’s still best practice to follow the specification.

If you have elements with IDs that start with a number and you need to select them using querySelector in JavaScript, you can still do so.

You just need to escape the ID properly using the CSS selector syntax. Here’s how you can do it:

// Assuming the ID is "123example"
var element = document.querySelector('#\31 23example');

// Or using template literals for readability
var id = '123example';
var element = document.querySelector(`#${CSS.escape(id)}`);

In the first example, \31 represents the digit 1 in Unicode escape syntax. The space after it is necessary because the space separates the digit from the rest of the ID.

The second example uses the CSS.escape() function, which properly escapes special characters in CSS selectors, ensuring the selector works correctly regardless of the characters in the ID.

Using one of these methods, you can select elements with IDs that start with a number using querySelector in JavaScript.