JMZ JMZ - 3 months ago 7
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>
<html>
<body>

<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>

<script>
function myFunction() {
document.querySelector("#57acafcbdb4bc607922b834f").style.backgroundColor = "red";
}
</script>

</body>
</html>

Answer

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:

document.querySelector('[id="57acafcbdb4bc607922b834f"]')

Or you can use document.getElementById():

document.getElementById('57acafcbdb4bc607922b834f')

See this code snippet:

console.log(document.querySelector('[id="57acafcbdb4bc607922b834f"]'))
console.log(document.getElementById('57acafcbdb4bc607922b834f'))
<div id="57acafcbdb4bc607922b834f"></div>

Comments