JavaScript 中 Cannot set property 'innerHTML' of Null 错误
“Cannot set property 'innerHTML' of Null”错误的发生有两个原因:
-
将
innerHTML
属性设置为空值(不存在的 DOM 元素)。 - 在声明 DOM 元素的 HTML 上方插入 JS 脚本标记。
下面是一个产生上述错误的示例代码
const el = null;
// ⛔️ Uncaught TypeError: Cannot set properties of null (setting 'innerHTML')
el.innerHTML = 'new value';
要解决“Cannot set property 'innerHTML' of Null”错误,请确保要设置 innerHTML
属性的 DOM 元素存在。 如果我们使用 getElementById()
方法并向其传递一个 DOM 中不存在的 ID,则最常发生该错误。
const el = document.getElementById('does-not-exist');
console.log(el); // 👉️ null
// ⛔️ Uncaught TypeError: Cannot set properties of null (setting 'innerHTML')
el.innerHTML = 'new value';
DOM 中不存在具有提供的 id 的元素,因此 getElementById
方法返回空值。
当我们尝试将 innerHTML
属性设置为空值时,会发生错误。
出现错误的另一个常见原因是在声明 DOM 元素之前放置 JS 脚本标记。
要解决“Cannot set property 'innerHTML' of null”错误,需要确保在声明 HTML 元素后将 JS 脚本标记放置在正文的底部。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
</head>
<body>
<!-- ⛔️ BAD - script is run before span exists ⛔️ -->
<script src="index.js"></script>
<span id="name">John</span>
</body>
</html>
JS 脚本标记添加在声明 span
元素的代码上方。 index.js 文件在创建 span
元素之前运行,因此我们无法从 index.js 文件访问该元素。
const el = document.getElementById('name');
console.log(el); // 👉️ null
// ⛔️ Cannot set properties of null (setting 'innerHTML')
el.innerHTML = 'Alice';
相反,必须将 JS 脚本标记移动到它尝试访问的 DOM 元素下方。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
</head>
<body>
<span id="name">John</span>
<!-- ✅ GOOD - span already exists ✅ -->
<script src="index.js"></script>
</body>
</html>
现在我们可以从 index.js 文件访问 span
元素。
const el = document.getElementById('name');
console.log(el); // 👉️ null
// ✅ Works
el.innerHTML = 'Alice';
现在 HTML 元素是在 index.js 脚本运行之前创建的,我们可以访问 DOM 元素并设置它的 innerHTML
属性。
总结
在以下情况下会发生“Cannot set property 'innerHTML' of Null”错误:
-
尝试将
innerHTML
属性设置为空值(不存在的 DOM 元素) - 在声明 DOM 元素之前插入 JS 脚本标签
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
如何在 JavaScript 中合并两个数组而不出现重复的情况
发布时间:2024/03/23 浏览次数:86 分类:JavaScript
-
本教程介绍了如何在 JavaScript 中合并两个数组,以及如何删除任何重复的数组。