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
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。