Javascript 无法读取属性';追加儿童';空JS的定义
我的JS代码有问题 我一直得到以下错误 未捕获的TypeError:无法读取null的属性“appendChild” JS代码:Javascript 无法读取属性';追加儿童';空JS的定义,javascript,html,css,Javascript,Html,Css,我的JS代码有问题 我一直得到以下错误 未捕获的TypeError:无法读取null的属性“appendChild” JS代码: const weatherIcon=document.getElementById('weather-icon'); const icon=document.createElement('img'); icon.setAttribute('id','icon'); icon.src=”http://openweathermap.org/img/w/50n.png";
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(图标);
weatherIcon.appendChild(图标)//此行有错误
您的脚本可能是在DOM完全加载之前执行的。试试看。这将确保只有在DOM完全加载后才能执行内部代码
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(图标);
weatherIcon.appendChild(图标);
});代码>
适用于Meth这意味着weatherIcon
无法找到ID为“weather icon”的元素。可能您正在加载DOM之前运行此代码。#weather icon
在执行JS时不存在<代码>文档。getElementById(“天气图标”)
正在返回null
。