0

I am having an issue with my JS code.

I keep getting the following error

Uncaught TypeError: Cannot read property 'appendChild' of null

JS Code:

    const weatherIcon = document.getElementById('weather-icon');

    const icon = document.createElement('img');
    icon.setAttribute('id', 'icon');
    icon.src = "http://openweathermap.org/img/w/50n.png";
    console.log(icon);
    weatherIcon.appendChild(icon);    //error is on this line
<div id="weather-data">
          <div id="weather-icon">
              
            </div>
    </div>
לבני מלכה
  • 15,925
  • 2
  • 23
  • 47
Adeel Hussain
  • 31
  • 1
  • 6

1 Answers1

1

Probably your script is executing before the DOM fully loaded. Try with DOMContentLoaded. This will ensure that the code inside will be executed only after the DOM is fully loaded.

document.addEventListener('DOMContentLoaded', function(){
  const weatherIcon = document.getElementById('weather-icon');

  const icon = document.createElement('img');
  icon.setAttribute('id', 'icon');
  icon.src = "http://openweathermap.org/img/w/50n.png";
  console.log(icon);
  weatherIcon.appendChild(icon);
});
<div id="weather-data">
  <div id="weather-icon"></div>
</div>
Giulio Bambini
  • 4,695
  • 4
  • 21
  • 36