Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
493 views
in Technique[技术] by (71.8m points)

javascript - console.log of element.children shows 0 length but has three entries when expanded later

In my javascript, I have two elements.

I have logged the two elements and it shows...

Element 1.

enter image description here

Element 2.

enter image description here

There are problem.

When I console.log the elements.children they obviously return some HtmlCollections

You will understand what the following means in a minute: But the weird thing is, that one HtmlCollection is empty (and has a length of 0), but has 3 elements (and has a length of 3).

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

Element 1 children & length:

enter image description here

Element 2 children & length: (the messed up one)

enter image description here

Does anyone have any idea what is going on here?

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

Thanks in advance! All help appreciated.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

Tooltip saying "Object value at left was shapshotted when logged, value below was evaluated just now."

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...