How to fix ReferenceError: Document is not defined in JavaScript

Updated onbyAlan Morel
How to fix ReferenceError: Document is not defined in JavaScript

Depending on your environment and setup, you can run into an error when you try to reference the document object.

Specifically, the error will look like this:

BASH
ReferenceError: document is not defined

In this post, we'll look at the most common reasons for this error and how to best avoid getting them.

On Node

The most common reason for this error is because you're using Node.

That is to say, you are trying to access the document object on the server, but the server does not have access to the document object because it lives on the browser.

Node is a server-side runtime so if you're on Node, you cannot reference the document object, which is an in-memory representation of the Document Object Model.

That also includes when you're doing server-side rendered applications, which can sometimes have universal code that can run on both the server and the browser.

On Browser

The most common reason for getting the reference error while on the browser is when you try to access the document object too early.

The best way to resolve this is to just move your code to the bottom of the page so that the document will be ready by the time your code references it.

HTML
<html> <head> <title>HTML page</title> </head> <body> <!-- [HTML](https://sabe.io/classes/html) here --> <!-- your script here --> <script type="module" src="index.js"></script> </body> </html>

If you want to check for the existence of the document object, you can use the following code:

JAVASCRIPT
if (typeof document !== "undefined") { // document exists } else { // document does not exist }

Once you can confirm that the document is available, you can then reference the document object without getting reference errors:

JAVASCRIPT
if (typeof document !== "undefined") { document.getElementById("my-element"); }

Conclusion

In this post, we looked at the most common reasons that causes the document reference error in JavaScript.

The main culprits are using server-side JavaScript like Node, or calling your script before the document is ready.

Hopefully, this was helpful to you. Thanks for reading!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.