Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - 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?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...