JMZ JMZ - 2 months ago 5x
CSS Question

How to fix an ID which isn't accepted as a query selector?

The following code returns the console error:

"Uncaught SyntaxError: Failed to execute 'querySelector' on 'Document': '#57acafcbdb4bc607922b834f' is not a valid selector."

Isn't HTML5 supposed to accept IDs beginning with a number? Is there a workaround for a situation where IDs of this type are needed?

<!DOCTYPE html>

<h2 id="57acafcbdb4bc607922b834f">A heading with class="example"</h2>
<p>A paragraph with class="example".</p>

<p>Click the button to add a background color to the first element in the document with class="example".</p>

<button onclick="myFunction()">Try it</button>

function myFunction() {
document.querySelector("#57acafcbdb4bc607922b834f").style.backgroundColor = "red";



IDs beginning with a number are indeed valid in HTML 5, but #57acafcbdb4bc607922b834f is not a valid CSS selector, and document.querySelector() uses CSS selectors.

You can use attribute selector instead:


Or you can use document.getElementById():


See this code snippet:

<div id="57acafcbdb4bc607922b834f"></div>