How to fix ReferenceError: Document is not defined in JavaScript
Table of Contents
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:
BASHReferenceError: 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:
JAVASCRIPTif (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:
JAVASCRIPTif (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!
- How to Install Node on Windows, macOS and Linux
- Getting Started with Express
- Create an RSS Reader in Node
- How to deploy a .NET app using Docker
- Best Visual Studio Code Extensions for 2022
- How to build a Discord bot using TypeScript
- How to deploy a Node app using Docker
- Learn how to use v-model with a custom Vue component
- How to Scrape the Web using Node.js and Puppeteer
- Getting Started with Moment.js
- Using Axios to Pull Data from a REST API
- How To Create a Modal Popup Box with CSS and JavaScript