【问题标题】:Why this is not a valid CSS selector using querySelectorAll in JS? [duplicate]为什么这不是在 JS 中使用 querySelectorAll 的有效 CSS 选择器? [复制]
【发布时间】:2017-03-23 03:51:34
【问题描述】:

我正在尝试使用 Vanilla JS 在我的 DOM 中找到所有带有 2x 类的 img 元素。我正在使用这样的querySelectorAll 方法:

document.querySelectorAll('img.2x');

但它会在控制台日志中抛出此错误:

Uncaught DOMException: Failed to execute 'querySelectorAll' on 'Document':
'img.2x' is not a valid selector.

为什么img.2x 不是一个有效的选择器?谢谢。

【问题讨论】:

标签: javascript css


【解决方案1】:

虽然它确实看起来有效,但您需要明确转义任何以 CSS 类开头的数字才能在选择器中使用它:

document.querySelectorAll('img.\\2x');

【讨论】:

  • 啊,好吧!我使用了 W3C HTML 验证器,它不会抛出任何错误。这仅发生在 JS 对,但在 HTML 中拥有一个以数字开头的类是有效的吗?
猜你喜欢
  • 2017-09-15
  • 2021-07-09
  • 2018-12-26
  • 2011-05-26
  • 2015-03-11
  • 2013-01-14
  • 2017-02-11
  • 2019-03-11
  • 2013-11-19
相关资源
最近更新 更多