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

Uncaught TypeError: Не удается прочитать свойство 'appendChild' из null

Я получаю следующую ошибку

Uncaught TypeError: Не удается прочитать свойство appendChild из null

myRequest.onreadystatechange @script.js: 20

с моим следующим кодом

// index.html 
<html>
    <head>
        <title>Simple Page</title>
    </head>
    <body>
        <div id="mainContent">
            <h1>This is an AJAX Example</h1>
        </div>
        <script type="text/javascript" src="script.js"></script>
    </body>
</html>

И вот мой файл JavaScript

// script.js
// 1. Create the request

var myRequest;

// feature check!
if(window.XMLHttpRequest) { // Firefox, Safari
    myRequest = new XMLHttpRequest();
} else if (window.ActiveXObject){ // IE
    myRequest = new ActiveXObject("Microsoft.XMLHTTP");
}


// 2. Create an event handler for our request to call back 
myRequest.onreadystatechange = function() {
    console.log("We were called!");
    console.log(myRequest.readyState);
    if(myRequest.readyState === 4){
        var p = document.createElement("p");
        var t = document.createTextNode(myRequest.responseText);
        p.appendChild(t);
        document.getElementById("mainContent").appendChild(p);
    }
};

// 3. open and send it
myRequest.open("GET","simple.txt", true);

// any parameters?
myRequest.send(null);

И вот содержимое simple.txt

Это содержимое простого текстового файла.

Я положил тег script внизу html как это предложил @Tejs здесь, но я все еще получаю эту ошибку.

4b9b3361

Ответ 1

На вашей странице нет элемента с идентификатором "mainContent", когда выполняется ваш обратный вызов.

В строке:

document.getElementById("mainContent").appendChild(p);

раздел document.getElementById("mainContent") возвращает null

Ответ 2

Признаки, связанные с ошибками, исправления ошибок и ошибок, связанных с ошибками, и исправления нагрузки

window.addEventListener('load', create, false);

function create() {
  // Crear nodo de tipo Element
  var parrafo = document.createElement("p");

  // Crear nodo de tipo Text
  var contenido = document.createTextNode("Hola Mundo!");

  // Añadir el nodo Text como hijo del nodo tipo Element
  parrafo.appendChild(contenido);

  // Añadir el nodo Element como hijo de la pagina
  document.body.appendChild(parrafo);
}

Ответ 3

Используйте querySelector, встроенный в getElementById();

var c = document.querySelector('#mainContent');
    c.appendChild(document.createElement('div'));