JavaScript报错:Cannot read properties of null (reading 'style')求助
解决"Uncaught TypeError: Cannot read properties of null (reading 'style')"报错
这个报错的核心是document.getElementById('splash')返回了null——说白了就是你的代码执行时,页面上找不到id为splash的元素。常见原因和解决办法如下:
常见原因
- 代码执行时机太早:DOM还没加载完成,就去获取元素了
- 元素不存在或id错误:页面里根本没有id为
splash的元素,或者id拼写有误(比如大小写不对、多打/少打字符)
解决办法
等DOM加载完成再执行代码
要么把代码放到DOMContentLoaded事件监听里,要么把script标签挪到body最后面:// 方式1:监听DOM加载完成事件 document.addEventListener('DOMContentLoaded', function() { const splashElement = document.getElementById('splash'); if (splashElement) { splashElement.style.display = 'none'; console.log("Already shown"); } else { console.warn("没找到id为splash的元素"); } }); // 方式2:把script标签放在</body>之前 // 确保页面元素都加载完成后再执行JS检查元素id是否正确
打开HTML文件,确认确实存在<div id="splash">...</div>这类元素,id的拼写(包括大小写)要和JS里的splash完全一致,别犯低级拼写错误。增加空值判断兜底
哪怕前面的步骤都做了,加一层判断也能避免报错:const splashElement = document.getElementById('splash'); if (splashElement) { splashElement.style.display = 'none'; console.log("Already shown"); }
内容的提问来源于stack exchange,提问作者salouh
相关产品推荐
相关产品推荐

