Search code examples
domnodesgetelementsbytagname

Why is childNodes not working in this script?


I am new to JS and trying to learn some basic stuff. I have spent hours on this but i don't think it should be that difficult. For some reason, my computer is not recognizing that I am asking for childNodes.

This is a simply script that is only trying to count the number of li tags I have. I know there are other ways to do this but i am trying to learn this way.

<title>To-Do List</title>
<script>
    function findComments(){
        var bodyTag = document.getElementsByTagName("ol");
        var count = 0;
        for(var i=0;i<bodyTag.childNodes.length;i++){
            if(bodyTag.childNodes[i].nodeType == 1){
                count++;
            }
        }
        alert(count);       
    }
    window.onload = findComments;
</script>

<!--List is declared-->
<ol id="toDoList">
    <!--List Items are created-->
    <li>Mow the lawn</li>
    <li>Clean the windows</li>
    <li>Answer your email</li>
</ol>
<!--Main paragraph-->
<p id="toDoNotes">Make sure all these are completed by 8pm so you can watch the game on TV!</p>
    <script>
</script>


Solution

  • getElementsByTagName returns an array, you need to retrieve its first element (and change the name from bodyTag to olTag or something since it's not the body tag and confused the heck out of me trying to make sense of your code)

    function findComments(){
        var ol = document.getElementsByTagName("ol")[0];
        var count = 0;
        for(var i=0;i<ol.childNodes.length;i++){
            if(ol.childNodes[i].nodeType == 1){
                count++;
            }
        }
        alert(count);       
    }
    

    And here's what you really should do now that you know what's wrong with your code

    var ol = document.getElementsByTagName("ol")[0];
    var liCount = ol.getElementsByTagName("li").length;