JavaScript 中 Cannot read properties of undefined(reading scrollHeight) 错误

“Cannot read properties of undefined(reading scrollHeight)”错误的发生有两个原因:

  1. 访问未定义值(不存在的 DOM 元素)上的 scrollHeight 属性。
  2. 在声明 DOM 元素的 HTML 上方插入 JS 脚本标记。

下面是产生上述错误的一个示例。

const elements = [];

// ⛔️ Uncaught TypeError: Cannot read properties of undefined (reading 'scrollHeight')
const height = elements[0].scrollHeight;

确保 DOM 元素存在

要解决“Cannot read properties of undefined(reading scrollHeight)”错误,请确保我们正在访问现有 DOM 元素上的属性。

在调用 getElementsByClassName 方法后越界访问数组索引时,通常会发生此错误。

const elements = document.getElementsByClassName('does-not-exist');
console.log(elements); // 👉️ []

// ⛔️ Uncaught TypeError: Cannot read properties of undefined (reading 'scrollHeight')
const scrollHeight = elements[0].scrollHeight;

我们为 getElementsByClassName 方法提供了一个无效的类名,因此该方法返回了一个空的类数组对象。

在不存在的索引处访问数组将返回 undefined

如果我们访问 undefined 的 scrollHeight 属性,则会发生错误。


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

要解决“Cannot read properties of undefined (reading ‘scrollHeight’)”错误,请将 JS 脚本标签放在 body 标签的底部。

JS 脚本应在声明 DOM 元素后运行。

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
  </head>
  <body>
    <!-- ⛔️ BAD - script is run before div exists ⛔️ -->
    <script src="index.js"></script>

    <div class="box">Hello</div>
  </body>
</html>

请注意 ,我们在创建 DOM 元素的 HTML 代码上方插入了 JS 脚本标记。

这意味着在 index.js 文件中将无法访问 div 元素。

const elements = document.getElementsByClassName('box');
console.log(elements); // 👉️ []

// ⛔️ cannot read property 'scrollHeight' of undefined
const scrollHeight = elements[0].scrollHeight;

我们应该将 JS script 标签放在 body 标签的底部,在它需要访问的 HTML 元素之后。

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
  </head>
  <body>
    <div class="box">Hello</div>

    <!-- ✅ GOOD - div already exists ✅ -->
    <script src="index.js"></script>
  </body>
</html>

现在我们可以访问 index.js 文件中的 div 元素。

const elements = document.getElementsByClassName('box');
console.log(elements); // 👉️ [div.box]

// ✅ Works
const scrollHeight = elements[0].scrollHeight;
console.log(scrollHeight); // 👉️ 18

scrollHeight 属性将值四舍五入为整数。 如果我们需要小数值,请改用 getBoundingClientRect() 方法。