无法在 JavaScript 中读取 Null 的属性“样式”

无法在 JavaScript 中读取 Null 的属性“样式”

Cannot read property ‘style’ of Null in JavaScript

出现“无法读取 null 的属性‘style’”错误的主要原因有两个:

  1. 访问style不存在的 DOM 元素的属性。
  2. 在声明 DOM 元素的 HTML 上方插入 JS 脚本标记。

无法读取 null 的属性样式

下面是错误如何发生的示例。

索引.js
const example = null; // ⛔️ Uncaught TypeError: Cannot read properties of null (reading 'style') console.log(example.style);

getElementById()如果您使用该方法并将其传递id给 DOM 中不存在的方法,则最常发生该错误。

索引.js
const box = document.getElementById('does-not-exist'); console.log(box); // 👉️ null // ⛔️ Cannot read properties null (reading 'style') box.style.color = 'blue';

要解决“无法读取 null 的属性‘style’”错误,请确保您正在访问该style属性的 DOM 元素存在。

在示例id中,DOM 中不存在具有提供的元素,因此该getElementById方法返回null当我们尝试访问style
一个值的属性时,
null我们得到了错误。

出现错误的另一个常见原因是在声明 DOM 元素之前放置 JS 脚本标记。

要解决“Cannot read property ‘style’ of null”错误,请确保在声明 HTML 元素后将 JS 脚本标记放置在正文的底部。

索引.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <!-- ⛔️ BAD - Script is run before HTML is declared ⛔️ --> <script src="index.js"></script> <div id="box" style="color: green">Hello</div> </body> </html>

我们在声明元素之前放置了 JSscript标记div,因此
index.js文件在创建 DOM 元素之前运行。

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

索引.js
const box = document.getElementById('box'); console.log(box); // 👉️ null // ⛔️ Cannot read properties null (reading 'style') box.style.color = 'blue';

您必须将 JSscript标记移动到正文的底部,在 HTML 元素之后。

索引.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div id="box" style="color: green">Hello</div> <!-- ✅ GOOD - Script is run after elements are declared ✅ --> <script src="index.js"></script> </body> </html>

现在 div 元素在index.js文件中可用。

索引.js
const box = document.getElementById('box'); console.log(box); // 👉️ the div element // ✅ works box.style.color = 'blue';

既然 HTML 元素是在index.js脚本运行之前创建的,我们就可以访问 DOM 元素了。

结论

在以下情况下会发生“无法读取 null 属性‘style’”错误:

  • 尝试访问值style上的属性,例如在使用无效标识符null调用之后
    getElementById
  • script在声明 DOM 元素之前插入 JS标签