-2

I have been doing trying to read a json file in javascript and showing it on my simple html. The JSON file looks something like this

{"candidates":
    [
        {
         "name":"John Doe",
         "age":56,
        },
        {
         "name":Jane Doe",
         "age":50,
         }
    ]
}

So far I think I fetched the file correctly but still can't print them on the HTML because I get the error "Cannot read property 'appendChild' of null"

fetch('./assets/candidates.json')
    .then(function (response) {
        return response.json();
    })
    .then(function (data) {
        appendData(data);
    })
    .catch(function (err) {
        console.log('error: ' + err);
});
function appendData(data){
    const candidate = data['candidates'];
    var mainContainer = document.getElementById("candidate-box");
    for(var i = 0;i<candidate.length;i++){
        var myP= document.createElement('p');
        myP.textContent = candidate[i].name;
        mainContainer.appendChild(myP);
    }
}

I don't understand how the value is null. I am a complete beginner in JavaScript and I would appreciate if someone could help me.

0 Answers0