ReferenceError: document is not defined(javascript)

56 Views Asked by At

enter image description hereWhy after installing node.js, an error like that occurs after I run the code of various javascript commands, it seems it's not because the code is an error but because node.js doesn't want to connect to the server.

enter image description hereWhen I tried to check whether node.js was connected to localhost or not, it turned out it wasn't connected, so how do I get node.js to connect to 127.0.0.1:300?

1

There are 1 best solutions below

0
On

You are running your JavaScript file in node.js enviroment. The document object and its methods, like getElementById in your case, are part of the Web API provided by browsers for manipulating web pages and are not available in Node.js.

Why? Because, node.js is a JS runtime used primarily for server-side scripting and does not have a built-in Document Object Model (DOM) like a web browser does

You can read more about the Document interface here: Document API

To run your js script in the browser, add it as a script in your index.html file with the <script> tag. This will load your javascript when your HTML file is loaded in the browser. You can follow the steps mentioned here:

Use JavaScript within a webpage