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?
The read-only firstChild property of the Node interface returns the node's first child in the tree, or null if the node has no children. If the node is a Document , this property returns the first node in the list of its direct children. Note: This property returns any type of node that is the first child of this one.
The firstChild property returns the first child node of a node. The firstChild property returns a node object.
The browser insert a text node when there are white spaces or new lines in your code. You are targeting one of those.
Try
var img = document.querySelector('.object img');
var innerImageId = img.id;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With