3

I am just a beginner in DOM manipulation so sorry for a silly question. I have te following piece of HTML and JS code

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

The issue here is that the

document.getElementById("demo").innerHTML = list;

outputs undefined in the window. However, everything works fine when I use firstElementNode property. Or is it because the first child is Attr corresponding to the ID attribute? Thanks in advance.

olzha bala
  • 183
  • 1
  • 5
  • 15

4 Answers4

5

The solution is very simple. What i did miss that white spaces are also taken into account. So that is why the first

document.getElementById("demo").innerhtml

gave me undefined. If i remove whitespace and make elements as

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

everything works.

olzha bala
  • 183
  • 1
  • 5
  • 15
3

Your question is solved by the exercise itself:

Note: Whitespace inside elements is considered as text, and text is considered as nodes. If you add whitespace before the first LI element, the result will be "undefined".

Since you have a line break after your ul element, firstChild returns that line break to your variable list which is what gives you the undefined.

Lixus
  • 511
  • 2
  • 12
3

firstChild is the first child node regardless of type. It can be any node type, including text nodes and comments.

firstElementChild on the other hand is the first child node that is an element.

In your case, the first child is a text node, specifically the whitespace before the first <li> tag.
Text nodes don't have an innerHTML property and that's why you get undefined.

Lennholm
  • 7,205
  • 1
  • 21
  • 30
2

after reading w3schools example it says that you shuldnt use a whitespace before the li element. So if you content your ul to look like:

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

the selector shuldnt return undefined

Orges_Kreka
  • 41
  • 1
  • 5