Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReferenceError: document is not defined (in plain JavaScript)

Tags:

javascript

I get the a "ReferenceError: document is not defined" while trying to

var body = document.getElementsByTagName("body")[0]; 

I have seen this before in others code and didn't cause any trouble. Why is it now? The companied HTML page is just a div inside the body.

<!DOCTYPE html> <html> <head lang="en">     <meta charset="UTF-8">     <title></title>     <link rel="stylesheet" type="text/css" href="css/quiz.css" />     <script type="text/javascript" src="js/quiz.js"></script> </head> <body>      <div id="divid">Next</div>  </body> </html> 

the code is the following:

(function(){         var body = document.getElementsByTagName("body")[0];          function Question(question, choices, correctAns) {             this.question = question;             this.choices = choices;             this.correctAns = correctAns;         }          Question.prototype.checkAns = function(givenAns){             if (this.correctAns === givenAns) {                 console.log("OK");             }         };          function Quiz() {             this.questions = [];         }          Quiz.prototype.showAllQuestions = function(){             this.questions.forEach(function(questions){                 console.log(questions.question);             });         };          Quiz.prototype.showQuiz = function(){             this.questions.forEach(function(questions){                  for (var i=0; i < questions.choices.length; i+=1) {                     body.innerHTML(                             "<input type=\"radio\" name=\"sex\" value=\"male\">"                              + questions.choices[i] + "<br>");                 }              });         };          var q1 = new Question("What is red?", ["Color","Animal","Building"],1);         var q2 = new Question("Most popular music?", ["Latin","Pop","Rock"],2);         var quiz = new Quiz();          quiz.questions.push(q1);         quiz.questions.push(q2);         quiz.showAllQuestions();           })(); 

Try the whole code in this link HERE

like image 509
limitcracker Avatar asked Jul 09 '14 07:07

limitcracker


People also ask

How do you fix the error require is not defined in JavaScript?

To solve the "ReferenceError require is not defined" error, remove the type property if it's set to module in your package. json file and rename any files that have a . mjs extension to have a . js extension.

What is a ReferenceError in JavaScript?

The ReferenceError object represents an error when a variable that doesn't exist (or hasn't yet been initialized) in the current scope is referenced. ReferenceError is a serializable object, so it can be cloned with structuredClone() or copied between Workers using postMessage() .

How do you define a document in JavaScript?

JavaScript is a language with its own syntax and built in types. document is not defined in the JavaScript (also more formally known as ECMAScript) specification. document is provided as an object API by the JavaScript "host" environment, which in a web page scenario, is the user agent (also known as the browser).

Is not defined $( document?

Basically $ is an alias of jQuery() so when you try to call/access it before declaring the function, it will endup throwing this $ is not defined error . This usually indicates that jQuery is not loaded and JavaScript does not recognize the $. Even with $(document).


1 Answers

This happened with me because I was using Next JS which has server side rendering. When you are using server side rendering there is no browser. Hence, there will not be any variable window or document. Hence this error shows up.

Work around :

If you are using Next JS you can use the dynamic rendering to prevent server side rendering for the component.

import dynamic from 'next/dynamic'  const DynamicComponentWithNoSSR = dynamic(() => import('../components/List'), {   ssr: false })  export default () => <DynamicComponentWithNoSSR /> 

If you are using any other server side rendering library. Then add the code that you want to run at the client side in componentDidMount. If you are using React Hooks then use useEffects in the place of componentsDidMount.

import React, {useState, useEffects} from 'react';  const DynamicComponentWithNoSSR = <>Some JSX</>  export default function App(){  [a,setA] = useState(); useEffect(() => {     setA(<DynamicComponentWithNoSSR/>)   });   return (<>{a}<>) } 

References :

  1. https://nextjs.org/docs/advanced-features/dynamic-import#with-no-ssr
  2. https://reactjs.org/docs/hooks-effect.html
like image 84
Trect Avatar answered Sep 21 '22 23:09

Trect