迹忆客 专注技术分享

当前位置:主页 > 学无止境 > WEB前端 > JavaScript >

JavaScript 中 Failed to execute 'querySelector' on Document 错误

作者:迹忆客 最近更新:2022/12/13 浏览次数:

当我们使用带有以数字开头的标识符的 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');

JavaScript 中 Failed to execute 'querySelector' on Document 错误

标识符不能以一个数字、两个连字符或一个连字符后跟一个数字开头。

要解决“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 方法时不包含 # 符号。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

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 POST

发布时间:2024/03/23 浏览次数:96 分类:JavaScript

本教程讲解如何在不使用 JavaScript 表单的情况下发送 POST 数据。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便