How to fix error in code api used javascript

-1

I'm setting up a code working to Connect to an API with JavaScript.

In line 9 and 10:

app.appendChild(logo);
app.appendChild(container);

I have the following error:

Unhandled exception at line 9, column 1 in ms-appx-web://ee3edcbd-0963-4d4b-a1e7-09cd199e440e/js/main.js 0x800a138f - JavaScript runtime error: Unable to get property 'appendChild' of undefined or null reference.

What is the solution to enable the code to be successfully activated?

const app = document.getElementById('root');

const logo = document.createElement('img');
logo.src = 'logo.png';

const container = document.createElement('div');
container.setAttribute('class', 'container');

app.appendChild(logo);
app.appendChild(container);

var request = new XMLHttpRequest();
request.open('GET', 'https://ghibliapi.herokuapp.com/films', true);
request.onload = function () {

    // Begin accessing JSON data here
    var data = JSON.parse(this.response);
    if (request.status >= 200 && request.status < 400) {
        data.forEach(movie => {
            const card = document.createElement('div');
            card.setAttribute('class', 'card');

            const h1 = document.createElement('h1');
            h1.textContent = movie.title;

            const p = document.createElement('p');
            movie.description = movie.description.substring(0, 300);
            p.textContent = `${movie.description}...`;

            container.appendChild(card);
            card.appendChild(h1);
            card.appendChild(p);
        });
    } else {
        const errorMessage = document.createElement('marquee');
        errorMessage.textContent = `Gah, it's not working!`;
        app.appendChild(errorMessage);
    }
}

request.send();
javascript
api
asked on Stack Overflow May 4, 2019 by Khlood Al Esrawi • edited May 4, 2019 by Yong Quan

2 Answers

1

The problem is your element with id 'root' does not exist in your DOM.

answered on Stack Overflow May 4, 2019 by gabeekex
0

You need to have element with id root inside HTML document.

First line of your code is trying to find element with id root inside DOM:

const app = document.getElementById('root');

The error says:

Unable to get property 'appendChild' of undefined or null reference.

So, your app variable is null or undefined, which mean the method document.getElementById does not find any element with id root.

Also you have to make sure that script is fired after DOM is loaded, otherwise script will not find element with id root even if this element is inside of HTML document.

To make sure if the DOM is loaded you can insert script tag on the end of the body (not in the head) or you can surround script with additional function:

window.onload = function() {
   // here is the place for your script
}
answered on Stack Overflow May 4, 2019 by Marek • edited May 4, 2019 by Marek

User contributions licensed under CC BY-SA 3.0