I was writing some code the other day, and for some reason, I had no idea why this happened, but this was part of the code that I had written.
var item = document.getElementByClass('object');
var innerImageId = item.firstChild.id;
I went over this code a lot of times. The problem of this code is that the value of innerImageId is undefined. The firstChild of item is an image. I need to get the id of the image, but no matter how many times I went over the code, it did not work. Here is the HTML file of the code.
<div class="object inventory-box">
<img src="image.png" id="sample-image">
</div>
Doesn't this seem correct? Well, I did some debugging in Google Chrome, and it turns out that there are 3 nodes in the div "object". The id of the first and the last node was undefined, but the 2nd one was "sample-image".
I then tried "firstElementChild" instead of "firstChild", and this worked well.
Then just to test it out, I did something like this-
<div class="object inventory-box">
<img src="image.png" id="sample-image">
</div>
(or with multiple lines of unnecessary whitespace)
but it still shows 3 nodes, the enter symbol, the div, and another enter symbol.
This problem keeps occurring in Chrome, Internet Explorer and Firefox.
Can someone please explain why there are these random 2 extra nodes?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…