Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does firstChild not return the first element?

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?

like image 405
Ronit Joshi Avatar asked Dec 04 '15 19:12

Ronit Joshi


People also ask

What is the first child of a node?

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.

Which property would you use to get the first child node of a node?

The firstChild property returns the first child node of a node. The firstChild property returns a node object.


1 Answers

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;
like image 132
L. Catallo Avatar answered Oct 13 '22 05:10

L. Catallo