JavaScript firstChild 返回 undefined

olz*_*ala 3 javascript dom

我只是 DOM 操作的初学者,很抱歉问一个愚蠢的问题。我有以下一段 HTML 和 JS 代码

<ul id="myList">
    <li>Coffee</li>
    <li>Tea</li>
</ul>

<p>Click the button to get the HTML content of the list's first child node.</p>

<button onclick="myFunction()">Try it</button>

<p><strong>Note:</strong> Whitespace inside elements is considered as text, and text is considered as nodes.</p>

<p>If you add whitespace before the first LI element, the result will be "undefined".</p>

<p id="demo"></p>
<p id="demo2"></p>

<script>
    function myFunction() {
        var list = document.getElementById("myList").firstChild.innerHTML;
        document.getElementById("demo").innerHTML = list;
        var x=document.getElementById("myList").childNodes[0];
        document.getElementById("demo2").innerHTML=x.nodeName;      
    }
</script>
Run Code Online (Sandbox Code Playgroud)

这里的问题是

document.getElementById("demo").innerHTML = list;
Run Code Online (Sandbox Code Playgroud)

在窗口中输出未定义。但是,当我使用 firstElementNode 属性时,一切正常。还是因为第一个孩子是ID属性对应的Attr?提前致谢。

olz*_*ala 5

解决方法很简单。我确实错过了空白也被考虑在内。所以这就是为什么第一个

document.getElementById("demo").innerhtml
Run Code Online (Sandbox Code Playgroud)

给了我未定义。如果我删除空格并将元素设为

 <ul id="myList"><li>Coffee</li><li>Tea</li></ul>
Run Code Online (Sandbox Code Playgroud)

一切正常。