【问题标题】:DOMException: Failed to execute 'querySelectorAll' on 'Document': '.u28suggest li:first a' is not a valid selectorDOMException:无法在“文档”上执行“querySelectorAll”:“.u28suggest li:first a”不是有效的选择器
【发布时间】:2021-07-19 21:50:42
【问题描述】:

我正在尝试执行这一行并得到以下错误

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

错误:

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

我该如何解决这个问题?

【问题讨论】:

    标签: javascript


    【解决方案1】:

    正如错误消息告诉你的那样,那是not a valid selector,特别是:first 部分,这是一个仅限jQuery 的东西,而不是CSS。相当于在 jQuery 中使用 DOM 和 CSS 的含义是:

    // 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 在这里是错误的,这就是我们想要的,但它会咬你。 :-)

    【讨论】:

      猜你喜欢
      • 2018-11-04
      • 2018-10-14
      • 1970-01-01
      • 2020-05-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多