DOMException:无法在“文档”上执行“querySelectorAll”:“.u28suggest li:first a”不是有效的选择器

问题描述

我正在尝试执行此行并出现以下错误

if (document.querySelectorAll('.u28suggest li:first a').length > 0) {

错误

DOMException: 无法在“文档”上执行“querySelectorAll”:“.u28suggest li:first a”不是有效的选择器。

我该如何解决这个问题?

解决方法

正如错误消息告诉您的那样,那是 not a valid selector,特别是 :first 部分,它是仅 jQuery 的东西,而不是 CSS。等效于使用 DOM 和 CSS 的 jQuery 中的含义是:

// Get the first match for `.u28suggest li`
const li = document.querySelector(".u28suggest li");
// If we got one and it has at least one `a` in it...
if (li && li.querySelectorAll("a").length > 0) {

或者使用可选链接,因为 undefined > 0 是假的:

if (document.querySelector(".u28suggest li")?.querySelectorAll("a").length > 0) {

请注意,您始终需要考虑左侧计算结果为 undefined 时的结果。同样,undefined > 0 在这里是假的,这就是我们想要的,但它会咬你。 :-)