简体   繁体   中英

Uncaught (in promise) TypeError: Cannot set properties of null (setting 'innerText') in OpenWetherMap API

function getResults(query) {
            fetch(`${api.base}weather?q=${query}&units=metric&appid=${api.key}`)
                .then(weather => {
                    return weather.json();
                }).then(displayResults);
        }
        function displayResults(weather) {
            let city = document.querySelector('.location .city');
            city.innerText = `${weather.name}, ${weather.sys.country}`;

            let now = new Date();
            let date = document.querySelector('.location .date');
            date.innerText = dateBuilder(now);

            let temp = document.querySelector('.current .temptater');
            temp.innerHTML = `${Math.round(weather.main.temp)}<span>°c</span>`;

            let weatherType = document.querySelector('.current .weather');
            weatherType.innerText = weather.weather[0].main;

            let hilow = document.querySelector('.hi-low');
            hilow.innerText = `${Math.round(weather.main.temp_min)}°c / ${Math.round(weather.main.temp_max)}°c`;
        }

When I am accessing a nested object in the array then this is showing

Uncaught (in promise) TypeError: Cannot set properties of null (setting 'innerText')

This happens only with

let weatherType = document.querySelector('.current .weather');
            weatherType.innerText = weather.weather[0].main;

This is a JSON file of API call

{
  "coord": {
    "lon": -0.1257,
    "lat": 51.5085
  },
  "weather": [
    {
      "id": 804,
      "main": "Clouds",
      "description": "overcast clouds",
      "icon": "04d"
    }
  ],
  "base": "stations",
  "main": {
    "temp": 10.96,
    "feels_like": 10.2,
    "temp_min": 9.65,
    "temp_max": 11.98,
    "pressure": 1039,
    "humidity": 80
  },
  "visibility": 10000,
  "wind": {
    "speed": 1.54,
    "deg": 340
  },
  "clouds": {
    "all": 90
  },
  "dt": 1639651705,
  "sys": {
    "type": 2,
    "id": 2019646,
    "country": "GB",
    "sunrise": 1639641643,
    "sunset": 1639669905
  },
  "timezone": 0,
  "id": 2643743,
  "name": "London",
  "cod": 200
}

Everything Else is running well, but I don't know why this is heppening. Any solution?

document.querySelector will return null when no matched elements are returned. It's probable that .current.weather doesn't refer to anything in your HTML.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM