Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js document is not defined

Why node.js does not recognize document.GetElementById? It says 'ReferenceError: document is not defined'. What can I do?

ReferenceError: document is not defined at Object.<anonymous> (C:\Users\Desktop\main.js:9:18) at Module._compile (module.js:460:26) at Object.Module._extensions..js (module.js:478:10) at Module.load (module.js:355:32) at Function.Module._load (module.js:310:12) at Function.Module.runMain (module.js:501:10) at startup (node.js:129:16) at node.js:814:3 
like image 238
Ela Avatar asked Aug 20 '15 18:08

Ela


People also ask

How do you fix document is not defined in node JS?

To solve the"ReferenceError: document is not defined" error, make sure to only use the document global variable on the browser. The variable relates to the Document Object Model, which represents a web page that is loaded in the browser and can't be used on the server side (e.g. in Node. js).

What does document is not defined mean?

Published May 04 2022. Here's how to fix the “referenceerror: document is not defined” error that you might have in Node. js or with a tool like Next. js. document is an object that's made available by the browser, and it's not available in a server-side JavaScript environment.

Why there is no document object in node JS?

it's because node. js doesn't run in browser like js. there is no document object to call methods from.

How do I fix JavaScript reference error?

Reference errors in Javascript are mainly thrown when an attempt is made to reference a variable that does not exist or is out of scope. Therefore, in the majority of cases, a ReferenceError can be fixed by making sure that the referenced variable is defined correctly and is being called in the correct scope.


2 Answers

document relates to the DOM (Document Object Model) in a web browser.

Node.js, however, is not a browser environment. It is a server environment, much like PHP or Perl, and as such, you can’t access the browser’s DOM or do anything specific to browser-hosted JavaScript.

The closest you could get is using something like browserify to include Node.js modules in your client-side code.

like image 86
brandonscript Avatar answered Sep 21 '22 13:09

brandonscript


You could use JSDom to add Dom support to Node. To make a variable global you can use either

GLOBAL.document = new JSDOM(html).window.document; 

or

global.document = new JSDOM(html).window.document; 

where html is your website as a string.

To use JSDom include it in your project with:

const jsdom = require("jsdom"); const { JSDOM } = jsdom; 

or in plain js with:

var jsdom = require("jsdom"); var JSDOM = jsdom.JSDOM; 

I hope this is answering your question.

like image 32
KOsimo Avatar answered Sep 19 '22 13:09

KOsimo