【问题标题】:Why !document.querySelectorAll not working for multiple id为什么 !document.querySelectorAll 不适用于多个 id
【发布时间】:2019-09-23 10:50:58
【问题描述】:

我目前有这个工作,但我需要添加一个额外的元素,所以我切换到 SelectorAll,但它不起作用

这是有效的

if(!document.getElementById('body_options_45')) {
//Do Stuff
}

当我添加第二个 ID 并切换到 selectorALl 时,它停止工作

if(!document.querySelectorAll('#body_options_45, #body_options_113')) {
   //Do Stuff
}

我在这里缺少什么?

【问题讨论】:

  • 您缺少querySelectorAll() 返回的内容。在文档中查找它,您会看到并了解如何使其工作。

标签: javascript jquery


【解决方案1】:

querySelectorAll() 返回一个 NodeListNodeLists are not arrays 但是,在这种特殊情况下,行为是相同的:空数组和空 NodeList 都是 truthy

![] //returns false
!emptyNodeList //returns false

要检查您的 NodeList 是否为空,请使用 length 属性:

if(document.querySelectorAll('#body_options_45, #body_options_113').length===0) {
   //do stuff
}

【讨论】:

    【解决方案2】:

    querySelectorAll 返回一个NodeList。您需要像这样检查lengthif (!document.querySelectorAll('#body_options_45, #body_options_113').length)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-02
      • 1970-01-01
      • 2012-07-13
      • 2015-12-13
      相关资源
      最近更新 更多