-1

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>
JMZ
  • 135
  • 2
  • 10
  • If you have control over the server-side html generation, you could generate ids like "hash_" + hashValue, and then your markup would look like `id="hash_57acafcbdb4bc607922b834f" which you can then select with querySelector("#hash_57acafcbdb4bc607922b834f"). – Christopher Aug 17 '16 at 18:45

2 Answers2

5

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>
Michał Perłakowski
  • 88,409
  • 26
  • 156
  • 177
1

// Escape the first digit with its unicode value in hex
document.querySelector('#\\35 1').style.color = 'green' 

// Or use getElementById 
document.getElementById('52').style.color = 'red'
<div id="51"> Element 51, should be green </div> 
<div id="52"> Element 52, should be red

Source: https://mothereff.in/css-escapes

c2huc2hu
  • 2,447
  • 17
  • 26