1

I'm trying to use the following database ID as a selector

5b4bb7d2685cfb094b1d46c3

The snippet is as follows:

document.querySelector('#5b4bb7d2685cfb094b1d46c3')
<button id="5b4bb7d2685cfb094b1d46c3">

When I try the selector, I get the following error:

Uncaught DOMException: Failed to execute 'querySelector' on 'Document': '#5b4bb7d2685cfb094b1d46c3' is not a valid selector.

What is wrong with my selector?

Ullas Hunka
  • 2,119
  • 1
  • 15
  • 28
Hoa
  • 19,858
  • 28
  • 78
  • 107

4 Answers4

10

Although this is valid in HTML, you can't use an ID starting with an integer in CSS selectors. You could use an attribute selector instead:

document.querySelector("[id='5b4bb7d2685cfb094b1d46c3']")

Or switch to using getElementById if that is an option:

document.getElementById("5b4bb7d2685cfb094b1d46c3")
CodingIntrigue
  • 75,930
  • 30
  • 170
  • 176
4

You can also use document.getElementById('5b4bb7d2685cfb094b1d46c3')

Programmer
  • 1,973
  • 1
  • 12
  • 20
0

You are allowed to start an ID with a digit, but with querySelector you have to follow the CSS standards.

In CSS, identifiers (including element names, classes, and IDs in selectors) can contain only the characters [a-zA-Z0-9] and ISO 10646 characters U+00A0 and higher, plus the hyphen (-) and the underscore (_); they cannot start with a digit, two hyphens, or a hyphen followed by a digit.

Use document.getElementById("5b4bb7d2685cfb094b1d46c3") instead.

Reference:

Uncaught SyntaxError: Failed to execute 'querySelector' on 'Document'

squancy
  • 565
  • 1
  • 7
  • 25
0

QuerySelector method uses CSS3 selectors for querying the DOM and CSS3 doesn't support ID selectors that start with a digit.

Nico Zimmer
  • 325
  • 1
  • 12