ReferenceError: document is not defined (in plain JavaScript)

匿名 (未验证) 提交于 2019-12-03 01:16:02

问题:

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.

       
Next

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[i] + "
"); } }); }; 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

回答1:

It depends on when the self executing anonymous function is running. It is possible that it is running before window.document is defined.

In that case, try adding a listener

window.addEventListener('load', yourFunction, false); // ..... or  window.addEventListener('DOMContentLoaded', yourFunction, false);  yourFunction () {   // some ocde  } 

Update: (after the update of the question and inclusion of the code)

Read the following about the issues in referencing DOM elements from a JavaScript inserted and run in head element:
- “getElementsByTagName(…)[0]” is undefined?
- Traversing the DOM



回答2:

try: window.document......

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


回答3:

Try adding the script element just before the /body tag like that

       
Next


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!