Javascript 中 TypeError: querySelectorAll is not a function 错误
出现“querySelectorAll is not a function”错误的原因有多种:
- 在不是有效 DOM 元素或文档对象的对象上调用方法。
- 将 JS 脚本标记放在声明 DOM 元素的代码上方。
- 拼写错误的 querySelectorAll 方法(区分大小写)。
下面是产生上述错误的一个代码示例
const boxes = document.querySelectorAll('.box');
console.log(boxes); // ?️ [div.box, div.box, div.box]
// ⛔️ TypeError: boxes.querySelectorAll is not a function
const blue = boxes.querySelectorAll('.blue');
我们成功地调用了第 1 行的 querySelectorAll 方法。
querySelectorAll 方法返回一个 NodeList,它是一个类数组对象。
然后我们尝试调用 NodeList 上的 querySelectorAll 方法并返回错误。
要解决“querySelectorAll is not a function”错误,请确保仅在有效的 DOM 元素或文档对象上调用 querySelectorAll 方法,并将 JS 脚本标记放在 body 标记的底部,在声明 DOM 元素后 。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
</head>
<body>
<div class="box">Box 1</div>
<div class="box">
<div class="blue">Box 2</div>
</div>
<div class="box">Box 3</div>
<!-- ✅ Your JS script here ✅ -->
<script src="index.js"></script>
</body>
</html>
这是 index.js 文件的代码。
const blue = document.querySelectorAll('.box .blue');
console.log(blue); // ?️ [div.blue]
我们在文档对象上调用了 querySelectorAll。 我们可以在文档对象或有效的 DOM 元素上调用该方法。
如果错误仍然存在,请确保没有拼错 querySelectorAll,因为它区分大小写。
如果我们调用该方法的元素有时不存在,可以在调用 querySelectorAll 方法之前有条件地检查该元素是否存在。
例如,一个基本的 DOM 元素有一个对象类型,所以我们可以在调用方法之前检查该值是否是一个对象并且包含 querySelectorAll 属性。
const box = null;
if (typeof box === 'object' && box !== null && 'querySelectorAll' in box) {
console.log(box.querySelectorAll('.blue'));
}
我们的 if 条件使用逻辑与 && 运算符,因此要运行 if 块,必须满足所有条件。
我们首先检查 box 变量是否存储了一个对象类型的值,因为 DOM 元素有一个对象类型。
然后我们检查变量是否不等于 null。 不幸的是,如果使用 console.log(typeof null),我们将得到一个“Ojbect”值,因此我们必须确保该值不为空。
然后我们知道我们可以安全地对该对象调用 querySelectorAll 方法。