Explain Codes LogoExplain Codes Logo

# Using querySelector with IDs that are numbers

javascript
css-escapes
attribute-selectors
cross-browser-compatibility
Alex KataevbyAlex Kataev·Nov 10, 2024
TLDR

You can select elements with numeric IDs using querySelector in two ways:

document.querySelector('#\\31 23'); // Escaping each digit document.querySelector('[id="123"]'); // Using an attribute selector as a bypass

Explanation of CSS escapes

The crux of the matter is this- we resort to CSS escapes when querying for numeric IDs. That means \\3 followed by a space prefaces every digit. This tactic stems from complying with Unicode representations.

Take the easier route, maybe?

Sure you can avoid the CSS conundrum and sail smoothly with getElementById:

document.getElementById('123');

But if you're a stickler for consistency across various selectors, querySelector is your true North.

Attribute selectors to the rescue

And then there's the heroes that come unannounced- attribute selectors. When you're in a spot with numeric IDs, they swoop in:

document.querySelector('[id="123"]');

Weren't expecting that now, were you?

God is in the details: Naming IDs

HTML5 says yay to numeric IDs but CSS? Well, you've seen what happens. So, why not slide in a descriptive prefix instead?

document.querySelector('#message123');

Ah! The sweet relief of readability!

Cross-browser compatibility: The real game

While CSS.escape sounds like your best bet, not all browsers play fair:

const escapedId = CSS.escape('123'); document.querySelector(`#${escapedId}`);

It always helps to keep your audience (read: browsers) in mind.

Automating escapes - opt for a reusable function

Who says you need to manually reinvent the wheel everytime? Presenting, cleanSelector, your knight in shining armour:

function cleanSelector(id) { return id.replace(/([0-9])/g, '\\3$1 '); } document.querySelector(`#${cleanSelector('123')}`);

Hocus pocus, and you're done!