迹忆客 专注技术分享

当前位置:主页 > 学无止境 > WEB前端 > JavaScript >

Javascript 中 TypeError: Cannot read property 'X' of NULL 错误

作者:迹忆客 最近更新:2023/02/20 浏览次数:

出现“Cannot read properties of null (reading 'X')”错误的主要原因有 3 个:

  1. 访问存储空值的变量的属性。
  2. 访问不存在的 DOM 元素的属性。
  3. 在声明 DOM 元素的 HTML 上方插入 JS 脚本标记。

如果大家尝试访问存储空值的变量的属性,例如 不存在的 DOM 元素。

这是一个例子。

const example = null;

// ⛔️ Uncaught TypeError: Cannot read properties of null
// (reading 'value')
example.value;

Javascript TypeError- Cannot read property 'value' of null

我们试图访问导致错误的 null 值的属性。

这是另一个例子。

const el = null;

// ⛔️ Uncaught TypeError: Cannot read properties of null
// (reading 'click')
el.click();

访问空值的属性

解决“Cannot read properties of null (reading 'X')”错误的一种方法是使用可选的链接 ?. 运算符,例如 obj?.address?.street

如果引用为空,可选的链接运算符将短路而不是抛出错误。

const example = null;

console.log(example?.value); // 👉️ undefined
console.log(example?.value?.moreNested); // 👉️ undefined

如果左侧的值为空值(nullundefined),则可选链接 ?. 运算符短路并返回 undefined

我们还可以以类似的方式使用逻辑与 && 运算符。

const example = null;

// 👇️ null
console.log(example && example.value && example.value.nested);

如果运算符左边的值是假的(例如 null),它不会计算右边的表达式,这样可以防止抛出错误。


在访问属性之前确保 DOM 元素存在

使用 DOM 元素时,“Cannot read properties of null (reading 'X') ”错误的发生有两个主要原因:

  1. 访问不存在的 DOM 元素的属性。
  2. 将 JS 脚本标记放在 index.html 文件中创建 DOM 元素的代码上方。

在使用 getElementById() 方法并向其传递一个不存在的 ID 后尝试访问属性时,通常会抛出该错误。

const el = document.getElementById('does-not-exist');
console.log(el); // null

// ⛔️ TypeError: Cannot read properties of null (reading 'value')
console.log(el.value);

我们指定了一个不存在的 id,并从 getElementById 方法中获得了一个空值。

尝试访问空值上的属性会导致错误。

确保我们访问的是正确的 DOM 元素,并添加条件检查以确保该元素在访问其属性之前存在。

const el = document.getElementById('not-exist');
console.log(el); // null


// ✅ 在访问属性之前检查元素是否存在
if (el?.value) {
  console.log(el.value);
} else {
  // 👇️ this runs
  console.log('element does not exist');
}

如果 el 变量存储一个 nullundefined 值,我们不会得到错误,相反我们短路返回 undefined 并且我们的 else 块运行。


将我们的 JS 脚本标签放在 body 标签的底部

Cannot read properties of null (reading 'X') ”错误的另一个常见原因是将 JS 脚本标记放在 index.html 文件中创建 DOM 元素的代码之上。

JS 脚本标签应该放在 HTML 元素声明之后。

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
  </head>
  <body>
    <script src="index.js"></script>

    <!-- ⛔️ BAD - 应该在 script 标签之上 ⛔️ -->
    <input id="first_name" value="John" />
  </body>
</html>

index.js 脚本位于输入元素上方,因此它无权访问它。

const el = document.getElementById('first_name');
console.log(el); // 👉️ null

// ⛔️ TypeError: Cannot read properties of null (reading 'value')
console.log(el.value);

在声明 HTML 元素之后,我们必须将 JS 脚本移动到正文的底部。

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
  </head>
  <body>
    <!-- ✅️ GOOD - JS 脚本之上的 HTML 元素 ✅️ -->
    <input id="first_name" value="John" />

    <script src="index.js"></script>
  </body>
</html>

现在我们可以访问 index.js 脚本中的 input 元素。

const el = document.getElementById('first_name');
console.log(el);

// ✅ works
console.log(el.value); // 👉️ "John"

HTML 代码是从上到下解析的,因此 script 标签必须放在 body 标签的底部,在它需要访问的所有 DOM 元素之后。


总结

要解决“Cannot read properties of null (reading 'X')”,请确保:

  1. 我们不是要访问存储空值的变量的属性。
  2. 我们不是在尝试访问不存在的 DOM 元素上的属性。
  3. 我们没有在 index.html 文件中声明 DOM 元素的 HTML 上方放置 JS 脚本标记。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

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 POST

发布时间:2024/03/23 浏览次数:96 分类:JavaScript

本教程讲解如何在不使用 JavaScript 表单的情况下发送 POST 数据。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便