JavaScript 中 Cannot read property ‘querySelectorAll’ of Null 错误
“Cannot read property ‘querySelectorAll’ of Null”错误的发生有两个原因:
- 对空值(不存在的 DOM 元素)调用
querySelectorAll()
方法。 - 将 JS 脚本标记放在声明 DOM 元素的 HTML 上方。
下面是产生上述错误的示例代码。
const el = null;
// ⛔️ Uncaught TypeError: Cannot read properties of null (reading 'querySelectorAll')
el.querySelectorAll('div.box');
要解决“Cannot read property ‘querySelectorAll’ of null”错误,请确保您用于获取元素的 ID 存在于 DOM 中。 该错误通常在向 getElementById
方法提供无效 ID 后发生。
const el = document.getElementById('does-not-exist');
console.log(el); // 👉️ null
// ⛔️ Cannot read properties of null (reading 'querySelectorAll')
el.querySelectorAll('div.box');
我们将一个不存在的 id 传递给 getElementById
方法并得到一个空值。 对空值调用 querySelectorAll()
方法会导致错误。
要解决“Cannot read property ‘querySelectorAll’ of null”错误,请将 JS 脚本标签放在 body 标签的底部。 该脚本应在创建 DOM 元素后运行。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
</head>
<body>
<!-- ⛔️ BAD - script runs before div exists ⛔️ -->
<script src="index.js"></script>
<div id="container">
<div class="box">Box 1</div>
<div class="box">Box 2</div>
</div>
</body>
</html>
请注意
,JS 脚本标记位于声明 div 元素的代码上方。 这意味着 index.js 文件无法访问 div 元素。
const el = document.getElementById('container');
console.log(el); // 👉️ null
// ⛔️ Cannot read properties of null (reading 'querySelectorAll')
el.querySelectorAll('div.box');
相反,我们应该将 JS 脚本标记移动到正文的底部,在它尝试访问的元素之后。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
</head>
<body>
<div id="container">
<div class="box">Box 1</div>
<div class="box">Box 2</div>
</div>
<!-- ✅ GOOD - div already exists ✅ -->
<script src="index.js"></script>
</body>
</html>
现在我们的 index.js 文件可以访问 DOM 元素。
const el = document.getElementById('container');
console.log(el); // 👉️ div#container
// ✅ Works
const boxes = el.querySelectorAll('div.box');
console.log(boxes); // 👉️ [div.box, div.box]
总结
尝试对 null 值调用 querySelectorAll
方法时发生“Cannot read property ‘querySelectorAll’ of Null”错误。
要解决该错误,需要在 DOM 元素可用后运行 JS 脚本,并确保仅在有效的 DOM 元素上调用该方法。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。