Last updated: Mar 2, 2024
Reading time·2 min
The "Failed to execute 'querySelector' on Document" error occurs when we use
the querySelector
method with an identifier that starts with a digit.
To solve the error, make sure that the class name or ID you're passing to the
querySelector
method doesn't start with a digit.
You might also get the error named as "Uncaught DOMException: Document.querySelector: '#XYZ' is not a valid selector" in Firefox.
Here's an example of how the error occurs.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <!-- ⛔️ id or class name starting with digit ⛔️ --> <div id="1box">Box 1</div> <div id="2box">Box 2</div> <script src="index.js"></script> </body> </html>
If we try to use the querySelector method to get the element, we'd get the error.
// ⛔️ Uncaught DOMException: Failed to execute 'querySelector' on 'Document': '#1box' is not a valid selector. // ⛔️ Uncaught DOMException: Document.querySelector: '#XYZ' is not a valid selector const first = document.querySelector('#1box');
querySelector
methodTo solve the error, pass the entire attribute to the querySelector
method or
update the identifier of your DOM element to not start with a digit.
Here's how you can pass the entire attribute to the querySelector
method to
avoid changing the id
of the DOM element.
// ✅ Works const first = document.querySelector("[id='1box']"); console.log(first); // 👉️ div#1box
Alternatively, you can change the identifier.
However, since you'd likely forget about this quirk, it's better to change your element's identifier to not start with a digit.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <!-- ✅ ID doesn't start with digit ✅ --> <div id="box1">Box 1</div> <div id="box2">Box 2</div> <script type="module" src="index.js"></script> </body> </html>
Now we can use the querySelector
method and everything works as expected.
const first = document.querySelector('#box1'); console.log(first); // 👉️ div#box1
Alternatively, you can use the
document.getElementById method, to which
you can pass an id
that starts with a digit.
const first = document.getElementById('1box'); console.log(first); // 👉️ div#1box
Notice that we don't include the hash #
symbol when using the getElementById
method.
You can learn more about the related topics by checking out the following tutorials: