. Advertisement .
..3..
. Advertisement .
..4..
Depending on your setup and environment, you can run into some errors when referencing the document object. How to fix referenceerror document not defined in Javascript?
This tutorial will give some most common reasons and the best solution for this error.
Why ReferenceError Document Is Not Defined In Javascript
The error looks like this:
ReferenceError: document is not defined
Here are some common reasons for this error:
On Node
The most common culprit behind this problem is using Node. This is because you have accessed the document on the server. Yet, this server lives on the browser and has no access to the object.
Node is a server-side runtime, which doesn’t allow you to reference the document object.
On Browser
If you access the object on the browser too early, you will get a referenceError document not defined in Javascript.
You should move your code to the page’s bottom to get the document ready:
<html>
<head>
<title>HTML page</title>
</head>
<body>
<!-- HTML here -->
<!-- your script here -->
<script type="module" src="index.js"></script>
</body>
</html>
The following code is used to check the object’s existence:
if (typeof document !== "undefined") {
// document exists
} else {
// document does not exist
}
Now you can reference the object without any reference error:
if (typeof document !== "undefined") {
document.getElementById("my-element");
}
How To Fix ReferenceError Document Not Defined In Javascript
In this case, the very first thing you need to do is make sure that you need to use the document object.
Shift your script tag at your body tag’s end or use the global variable in the browser. Write the code in the index.html file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<script src=”app.js”></script>
<title>ReferenceError: Document is not defined</title>
</head>
<body>
<h1>Body of the HTML Doc</h1>
<div id=”msg”>
<p>This is a message.</p>
</div>
</body>
</html>
Now, it is time to write the following code inside the app.js:
console.log("This is a ReferenceError: document is not defined");
var x = document.getElementById("msg");
console.log(x);
Here is the fix code:
console.log("Fixing Document is not defined in NodeJS");
if (typeof window !== "undefined") {
console.log("In Browser");
var x = document.getElementById("msg");
console.log(x);
}
else {
console.log("In nodeJS");
}
If your window object is undefined, you must have been running Javascript in Node.js. If not, you are in the browser and apply the solution in your project.
Conclusion
Despite its power, the document object still has various pitfalls, especially when you use it in a Node.js environment. Tet, the problem is well solved by the method in our above article.
How to fix ReferenceError document not defined in Javascript? Follow the steps to replace or use documents properly and be back to creating your web app.
Leave a comment