首页 > 解决方案 > 为什么 getElementByClassName 生成的集合被 js 视为长度为 0 而不是,尤其是在 console.loged 时

问题描述

有些东西我真的需要理解,但无法通过谷歌搜索找到答案。

在我的 index.html DOM 中,我有一个简单的 div(我们称之为“indexDiv”)。

我的项目文件中有另一个 html 文件(我们称之为 non-index.html,包含由 Word 生成的很长的 html 代码。

non-index.html 中的 html 包含在 3 个具有相同类名的 div 中:“DivClassName”。

使用 js,我将 non-index.html 中的 3 个 div 附加到我的 DOM 的 indexDiv 中。

在我的 js 代码的某处,我有以下内容function

function collection() {
    var myCollection= document.getElementsByClassName("DivClassName");// i.e., a collection of the 3 divs appended to the DOM from the non-index.html
    console.log(myCollection);
    console.log(myCollection.length);
    if (myCollection.length > 0) {
      console.log(myCollection);
    }
  }

第一个console.log(myCollection)打印长度为 3 的 HTMLCollection,其中 3 个 div 具有相同的className.

第二个console.log(myCollection.length)紧跟在第一个之后,打印 0。

第三个console.log(myCollection)根本没有被打印出来,这证实了myCollection.length它不是 > 0。

我无法理解这种行为。第一个 console.log 如何显示 3 个元素的集合(这是准确的,并且对应于我的 DOM 中具有相同 className 的元素的数量),而 javascript 在执行任何后续代码时将相同的集合视为长度为 0 ?

如果有人可以解释或指导我查看解释此行为的文档,我将非常感激。

非常感谢。

标签: javascript

解决方案


myCollection 我认为问题在于您从控制台读取的内容。让我们看这个修改过的例子:

function collection() {
    var myCollection= document.getElementsByClassName("DivClassName");
    console.log(myCollection); // HTMLCollection[..., ..., ...]
    console.log(myCollection.length); // 3
    if (myCollection.length > 0) { // true
      console.log(myCollection); // HTMLCollection[..., ..., ...]
    }
}

collection();

var myCollection = document.getElementsByClassName("DivClassName");

Array.from(myCollection).forEach(function(div) {
  div.remove();
});

console.log(myCollection); // HTMLCollection []

在控制台中,第一个和第三个日志在您打开它们之前不会更改……然后您会看到length: 0一行。我知道也许这不是正在发生的事情,但我想不出任何其他问题。


推荐阅读