A
A
Artyom2021-01-17 19:02:22
JavaScript
Artyom, 2021-01-17 19:02:22

Uncaught TypeError: Cannot set property 'innerHTML' of null - how to get DOM?

Hello everyone, I'm writing my mini-browser extension!
Here is my panel.html:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="/main.css">
</head>
<body>
    <ul class="nav__extensions">
        <li><a id="main" href="">Главная</a></li>
        <li><a id="vk_parse" href="">vk parse</a></li>
        <li><a id="facebook_parse" href="">facebook parse</a></li>
        <li><a href="">О нас</a></li>
        <li><a href="">Контакты</a></li>
    </ul>

    <div class="items_extensions" id="items_extensions">23423423</div>


</body>
</html>
<script src="background.js" defer></script>

Here is background.js:
window.onload = () => {
var requestURL = "http://mvs.com/feed/ajax";
var request = new XMLHttpRequest();
request.open('POST', requestURL)
request.responseType = 'json';
request.send()
request.onload = function() {
    var superHeroes = request.response;
    populateHeader(superHeroes);
}

function populateHeader(jsonObj) {
    const items = document.querySelector(".items_extensions")

    for (var key in jsonObj) {
        items.innerHTML = jsonObj[key]
        console.log(jsonObj[key])
    }

    console.log(jsonObj)
    console.log(items)
    // for (let i = 0; i < jsonObj.options.length; i++) {
    //     console.log(jsonObj.options[i])
    // }
}
}


Error in console:

Uncaught TypeError: Cannot set property 'innerHTML' of null
at populateHeader (background.js:16)
at XMLHttpRequest.request.onload (background.js:9)
populateHeader @ background.js:16
request.onload @ background.js:9
load (async)
window.onload @ background.js:7
load (async)
(anonymous) @ background.js:1


How to fix it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey delphinpro, 2021-01-17
@delphinpro

const items = document.querySelector(".items_extensions")

Before using, you need to check - is the variable really what we expect?
In your case, there is null, i.e. the element on the page was not found during the execution of this code.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question