本地开发遇Uncaught TypeError:无法设置null的innerHTML属性
修复本地环境中
Uncaught TypeError: resultContainer is null错误 问题背景
我有以下代码:
HTML代码
<!DOCTYPE html> <head> <title>Intro to Js</title> <link rel="stylesheet" type="text/css" href="css/style.css"> </link> <script type="text/Javascript" src="scripts/index.js"></script> </head> <body> <h1>Introduction to Javascript</h1> <hr/> <div id="ResultContainer"></div> </body> </html>
JavaScript文件(scripts/index.js)
var resultContainer = document.getElementById("ResultContainer"); resultContainer.innerHTML = "Setting up environment";
CSS文件(css/style.css)
body { margin-top: 20px; margin-left: 20px; } h1 { font-size: 50px; } #ResultContainer { font-size: 30px; margin-top: 30px; padding: 10px; width: 450 px; height: 200px; border: 1px solid black; }
本地运行时触发错误:
Uncaught TypeError: resultContainer is null
http://localhost:3000/scripts/index.js:6
相同代码在在线编辑器可正常运行,请问本地环境该如何修复?
错误原因
问题出在浏览器的加载执行顺序:你把JS引用放在了<head>标签内,浏览器会优先加载并执行这段JS代码,此时<body>中的ResultContainer元素还未被渲染到DOM中,document.getElementById自然找不到目标元素,返回null,后续尝试访问null的innerHTML属性就会抛出类型错误。
在线编辑器通常默认会将JS代码延迟到DOM完全加载后执行,所以不会出现这个问题。
解决方案
方案1:将<script>标签移到<body>末尾
这是最直观的解决方式,让浏览器先渲染完所有页面元素,再执行JS代码:
<!DOCTYPE html> <head> <title>Intro to Js</title> <link rel="stylesheet" type="text/css" href="css/style.css"> </head> <body> <h1>Introduction to Javascript</h1> <hr/> <div id="ResultContainer"></div> <!-- 移至body末尾 --> <script type="text/Javascript" src="scripts/index.js"></script> </body> </html>
方案2:通过DOMContentLoaded事件监听执行代码
在JS中添加事件监听,确保代码只在DOM加载完成后执行:
document.addEventListener('DOMContentLoaded', function() { var resultContainer = document.getElementById("ResultContainer"); resultContainer.innerHTML = "Setting up environment"; });
方案3:给<script>添加defer属性
defer属性会告诉浏览器延迟执行JS脚本,直到DOM解析完成:
<script type="text/Javascript" src="scripts/index.js" defer></script>
额外提示
你的CSS代码中有一处语法错误:width: 450 px;里的数值和单位之间多了空格,应该改为width: 450px;,否则宽度设置不会生效。
内容的提问来源于stack exchange,提问作者user51
相关产品推荐
相关产品推荐

