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,031
  • 1
  • 13
  • 27
Hoa
  • 19,004
  • 26
  • 72
  • 102

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
  • 71,301
  • 29
  • 165
  • 172
4

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

Programmer
  • 1,843
  • 1
  • 11
  • 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
  • 545
  • 1
  • 6
  • 24
0

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

Nico Zimmer
  • 312
  • 1
  • 12