JS Error with Ajax: TypeError: Cannot set property 'innerHTML' of null (not a duplicate, none of the other answers worked)

JS Error with Ajax: TypeError: Cannot set property 'innerHTML' of null (not a duplicate, none of the other answers worked)

当我的代码运行并应该编辑 Ajax 加载中的 DOM 元素时,它不起作用并给我一个错误:类型错误:无法设置 属性 'innerHTML' 为空。

我检查了几乎所有的东西,我相信我没有弄错 class 名字或任何东西。

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Ajax Crash Course</title>
</head>
<body>
     <button class="userBtn">Click for User</button>

    <br>
    <br>

    <div class="DOMInsertions"></div>

    <script src="ajax2.js"></script>
</body>
</html>

JavaScript:

const userBtn = document.querySelector('.userBtn');
let listNum = 0;


userBtn.addEventListener('click', userCall);

function userCall() {

    const xhr = new XMLHttpRequest;

    xhr.open('GET', 'user.json', true);

    xhr.onload = function() {
        if( xhr.status === 200 ){
            let user = JSON.parse(this.responseText);
            let { name, id, email } = user;

            let className = `userList_${listNum}`;

            textToDOM('h1', 'User:', 'heading');

            textToDOM('ul', 'Yo', className)

            let list = document.querySelector(className)

            list.innerHTML = `
            <li>ID: ${id} </li>
            <li>Name: ${name} </li>
            <li>Email: ${email}</li>
            `
            listNum++;
        }
    }

    xhr.send();
}

好的,我实际上已经重建了脚本并发现了一些问题:

DOMInsert 未明确定义。您可以通过向注入容器添加 ID 并通过 ID 引用它来解决此问题:

<div class="DOMInsertions" id="dominsert"></div>

然后使用这个:

document.getElementById('dominsert').appendChild(addition);

第二个问题是你的类名没有定义。因此,您的 "list" 未定义。