JavaScript 中 Failed to execute 'querySelector' on Document 错误
当我们使用带有以数字开头的标识符的 querySelector
方法时,会发生“Failed to execute 'querySelector' on Document”错误。 要解决该错误,请确保我们传递给 querySelector
方法的类名或 ID 不以数字开头。
下面是错误如何发生的示例。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
</head>
<body>
<!-- ⛔️ id or class name starting with digit ⛔️ -->
<div id="1box">Box 1</div>
<div id="2box">Box 2</div>
<script src="index.js"></script>
</body>
</html>
如果我们尝试使用 querySelector
方法来获取元素,我们会得到错误。
// ⛔️ Failed to execute 'querySelector' on 'Document'
const first = document.querySelector('#1box');
标识符不能以一个数字、两个连字符或一个连字符后跟一个数字开头。
要解决“Failed to execute 'querySelector' on Document”错误,请将整个属性传递给 querySelector
方法或更新 DOM 元素的标识符,使其不以数字开头。
下面介绍了如何将整个属性传递给 querySelector
方法以避免更改 DOM 元素的 ID。
// ✅ Works
const first = document.querySelector("[id='1box']");
console.log(first); // 👉️ div#1box
但是,由于我们可能会忘记这个怪癖,最好将元素的标识符更改为不以数字开头。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
</head>
<body>
<!-- ✅ ID doesn't start with digit ✅ -->
<div id="box1">Box 1</div>
<div id="box2">Box 2</div>
<script type="module" src="index.js"></script>
</body>
</html>
现在我们可以使用 querySelector
并且一切都按预期工作。
const first = document.querySelector('#box1');
console.log(first); // 👉️ div#box1
或者,我们可以使用 getElementById
方法,我们可以将以数字开头的 ID 传递给该方法。
const first = document.getElementById('1box');
console.log(first); // 👉️ div#1box
请注意
,我们在使用getElementById
方法时不包含#
符号。
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
如何在 JavaScript 中合并两个数组而不出现重复的情况
发布时间:2024/03/23 浏览次数:86 分类:JavaScript
-
本教程介绍了如何在 JavaScript 中合并两个数组,以及如何删除任何重复的数组。