Failed to execute 'querySelector' on Document in JS [Fixed]


Borislav Hadzhiev

2 min


Photo from Unsplash

Failed to execute 'querySelector' on Document #

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.

failed to execute queryselector on document

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.

// ⛔️ Failed to execute 'querySelector' on 'Document' const first = document.querySelector('#1box');
Identifiers can't start with a digit, two hyphens, or a hyphen followed by a digit.

Pass the entire attribute to the querySelector method #

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

Changing the identifier of your element #

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

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.