element.children 的 console.log 显示长度为 0,但稍后展开时包含三个条目

2022-01-30 00:00:00 javascript html htmlcollection

在我的 JavaScript 中,我有两个元素.

我已经记录了这两个元素,它显示了以下内容:

元素 1:

元素 2:

问题是:

  • 当我console.log每个元素的子元素(element.children)时,它显然会返回一个元素列表.
  • 但奇怪的是,一个元素是空的(长度为 0),但展开后有 3 个元素(长度为 3).

如果你阅读下面的元素子元素的日志,你就会明白我在说什么......

元素 1(这个按预期工作):

元素 2(有问题的元素):

有人知道这里发生了什么吗?孩子的数量怎么会有相互矛盾的报道?

我该如何解决这个问题?我需要遍历孩子,但它不会让我,因为长度显然是 0.

提前致谢!感谢所有帮助.

解决方案

当您将对象记录到控制台时,对象的当前状态不会被快照和显示(如您所料);相反,控制台获取对象的实时引用.当您在控制台中展开它时,您会看到展开它时的内容,而不是您登录时的内容.

它说左侧的对象值在记录时被快照,下面的值刚刚被评估."


但一般来说:我建议您使用浏览器内置的调试器和/或IDE.

In my JavaScript, I have two elements.

I have logged the two elements and it shows the following:

Element 1:

Element 2:

The problem is:

  • When I console.log the children of each element (element.children) it obviously returns a list of elements.
  • But the weird thing is, that one element is empty (and has a length of 0), but has 3 elements (and has a length of 3) once expanded.

If you read the logs below for the children of the elements, you will understand what I am talking about...

Element 1 (this one is working as expected):

Element 2 (the problematic one):

Does anyone have any idea what is going on here? How can there be contradictory reports of the number of children?

How do I fix this? I need to loop through the children, but it won't let me because the length is apparently 0.

Thanks in advance! All help appreciated.

解决方案

When you log objects to the console, the object's current state is not snapshotted and displayed (as you might expect); instead, the console gets a live reference to the object. When you expand it in the console, you see its contents as of when you expand it, not as of when you logged it. More on that in this question and its answers.

So apparently your collections are empty when you do your logging, and then gain their elements later. You just want to make your code wait until the collections are populated. For instance, if you're doing this immediately when your script is run, consider putting the script at the end of the document, right before the closing </body> tag.

The very subtle blue (i) icon next to the object has a tooltip that's useful; if you hover it you see:

It says "Object value at left was snapshotted when logged, value below was evaluated just now."


But generally: Rather than stumbling around in the dark with a console.log torch, I suggest turning on the lights using the debugger built into your browser and/or IDE.

相关文章