Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript firstChild returns undefined

Tags:

javascript

dom

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.

like image 319
olzha bala Avatar asked Dec 07 '25 17:12

olzha bala


1 Answers

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.

like image 144
olzha bala Avatar answered Dec 09 '25 06:12

olzha bala



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!