Fix - Failed to execute 'querySelector' on Document in JS

avatar

Borislav Hadzhiev

Tue Oct 19 20212 min read

Fix - 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 does not start with a digit.

failed to execute queryselector on document

Here's an example of how the error occurs.

index.html
<!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>

Now if we try to use the querySelector method to get the element we would get the error.

index.js
// ⛔️ 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.

To solve the "Failed to execute 'querySelector' on 'Document'" error pass the entire attribute to the querySelector method or update the identifier of your DOM element to not start with a digit.

This example shows how we can pass the entire attribute to the querySelector to avoid changing the id of the DOM element.

index.js
// ✅ Works const first = document.querySelector("[id='1box']"); console.log(first); // 👉️ div#1box

However, since it's very likely that you would forget about this quirk later on, it's better to change your element's identifier to not start with a digit.

index.html
<!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 and everything will work as expected.

index.js
const first = document.querySelector('#box1'); console.log(first); // 👉️ div#box1

Alternatively you could use the getElementById method to which you are able to pass an id that starts with a digit.

index.js
const first = document.getElementById('1box'); console.log(first); // 👉️ div#1box

Notice that we don't include the # symbol when using the getElementById method.

Use the search field on my Home Page to filter through my more than 1,000 articles.