Skip to content

DOM 元素是 空

快速摘要

你的 JavaScript tries 到 access DOM 元素那个做 不 exist, resulting in 'Cannot 读取属性的 空'.

为什么发生

  • script 运行之前 DOM 元素是 parsed

  • selector 做不 match 任何元素 (typo, 错误类/id)

  • 元素是 dynamically 添加但 查询运行之前它 是添加

最小示例

✗ 错误代码
const el = document.querySelector(".nonexistent");
el.textContent = "Hello"; // TypeError: Cannot read properties of null
✓ 修复代码
const el = document.querySelector(".my-element");
if (el) {
  el.textContent = "Hello";
} else {
  console.warn("Element not found");
}

总是检查如果元素 exists 之前 accessing 它的属性. Fix selector 如果它 是错误, or ensure script 运行之后元素是 in DOM.

如何诊断

  • 检查错误消息 — 'Cannot 读取属性的 空' indicates 空元素

  • Log 元素: console.log(document.querySelector('.my-类')) — 是它 空?

  • 验证 selector matches 元素 in HTML

如何修复

  • Move script 到端 的 <请求体> or 添加 defer

  • Wrap code in DOMContentLoaded 事件监听器

  • 添加空 检查之前 accessing 元素

  • Fix selector 到 match 正确元素

如何预防

  • Use defer on scripts or 位置它们 at 端的 <请求体>

  • 总是检查 for 空之前 using queried 元素

  • Use 事件 delegation for dynamically 添加元素

相关资源

相关术语

相关课程

相关练习

← 返回语言