Jordy337
Jordy337

Reputation: 420

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

When my code runs and is supposed to edit a DOM element in an Ajax onload, it doesn't work and gives me an error: TypeError: Cannot set property 'innerHTML' of null.

I have checked pretty much everything and I do believe I haven't made a mistake with class names or anything.

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

Upvotes: 0

Views: 79

Answers (1)

Schien
Schien

Reputation: 3903

Okay I have actually rebuilt the script and found a few issues:

DOMInsert is not well defined. You can fix this by adding an ID to your injection container and refer to it by the ID:

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

Then use this:

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

The second problem is that your className is nowhere defined. As a result, your "list" is undefined.

Upvotes: 1

Related Questions