# Using querySelector with IDs that are numbers
You can select elements with numeric IDs using querySelector
in two ways:
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
:
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:
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?
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:
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:
Hocus pocus, and you're done!
Was this article helpful?