Подтвердить что ты не робот

ReferenceError: документ не определен (в обычном JavaScript)

Я получаю "ReferenceError: document not defined" при попытке

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

Я видел это раньше в другом коде и не вызывал никаких проблем. Почему это сейчас? Сопутствующая HTML-страница - это просто div внутри тела.

<!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>

код выглядит следующим образом:

(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();


        })();

Попробуйте весь код в этой ссылке ЗДЕСЬ

4b9b3361

Ответ 1

Это зависит от того, когда запущена анонимная функция self. Возможно, он работает до window.document.

В этом случае попробуйте добавить слушателя

window.addEventListener('load', yourFunction, false);
// ..... or 
window.addEventListener('DOMContentLoaded', yourFunction, false);

yourFunction () {
  // some ocde

}

Обновление: (после обновления вопроса и включения кода)

Прочитайте следующее о проблемах при ссылке на элементы DOM из вставленного JavaScript и выполните в элементе head:
- "getElementsByTagName (...) [0]" есть undefined?
- Обход DOM

Ответ 2

Попробуйте добавить элемент script непосредственно перед тегом body/

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <link rel="stylesheet" type="text/css" href="css/quiz.css" />
</head>
<body>

    <div id="divid">Next</div>
    <script type="text/javascript" src="js/quiz.js"></script>
</body>
</html>

Ответ 3

попробуйте: window.document......

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