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


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.

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

// โ›”๏ธ 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.

// โœ… 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.

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

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.

const first = document.getElementById('1box'); console.log(first); // ๐Ÿ‘‰๏ธ div#1box

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

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee