为什么firstChild不返回第一个元素? [英] Why does firstChild not return the first element?
问题描述
我前几天写了一些代码,出于某种原因,我不知道为什么会发生这种情况,但这是我编写的代码的一部分。
var item = document.getElementByClass('object');
var innerImageId = item.firstChild.id;
我经常浏览这段代码。这段代码的问题是innerImageId的值是未定义的。项目的firstChild是一个图像。我需要获取图像的ID,但无论我多少遍了代码,它都不起作用。这里是代码的HTML文件。
< div class =object inventory-box>
< img src =image.pngid =sample-image>
< / div>
这不正确吗?好吧,我在谷歌浏览器中进行了一些调试,结果发现在对象中有3个节点。第一个和最后一个节点的ID是未定义的,但第二个是样本图像。
然后我尝试了firstElementChild而不是firstChild,并且这个效果很好。
然后,为了测试它,我做了这样的事情 - / p>
< div class =object inventory-box>
< img src =image.pngid =sample-image>
< / div>
(或者多行不必要的空格)
但它仍然显示3个节点,输入符号,div和另一个输入符号。
这个问题在Chrome,Internet Explorer和Firefox中不断出现。
有人可以解释为什么会有这些随机的2个额外节点吗?
当代码中有空格或新行时,浏览器将插入文本节点。
试试
var img = document.querySelector('。object img');
var innerImageId = img.id;
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 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;
这篇关于为什么firstChild不返回第一个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!