为什么js认为getElementByClassName生成的集合的长度为0,而不是0,特别是在console.loged时

问题描述 投票:1回答:1

我确实需要了解一些内容,无法通过谷歌搜索来找到答案。

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

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

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

使用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个div且具有相同className的长度为3的HTMLCollection。

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

第三个console.log(myCollection)完全没有打印,这确认myCollection.length不是> 0。

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

如果有人可以解释我或将我引导到解释此问题的文档,我将非常感谢。

非常感谢。

javascript
1个回答
1
投票

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行。我知道也许这不是正在发生的事情,但我想不出任何其他问题。

© www.soinside.com 2019 - 2024. All rights reserved.