javascripthtmlcollection

How to render [object HTMLCollection].length in an element's innerHTML?


I am looking to show that a HTMLCollection is a live list and NodeList is static. To do this I store the total number of divs, which is 1, on the page in a variable for each (g for HTML, q for Node). I do this using GetElementBy... and querySelector....respectively.

console.log(q.length) // 1

console.log(g.length) // 1

I then use JS to create a new div and append it to the page. Total divs now 2.

console.log(q.length) // 1

console.log(g.length) // 2

it all works fine in the console however, I cannot get g.length displayed correctly. I receive a TypeError. I dont quite understand how g.length can be null

ScreenShot: Chrome error

index.html file with JS

<!DOCTYPE html>
<html lang="en">
    <head>
<script>
    function newElement() {
        newDiv = document.createElement('div')
        newDiv.innerHTML = 'Div 2'
        document.getElementById('wrapper').appendChild(newDiv);
    }

    function updateStats() {
        document.getElementById('queryA').innerHTML = q;
        document.getElementById('getA').innerHTML = g;
        document.getElementById('queryAL').innerHTML = q.length;
        document.getElementById('getAL').innerHTML = g.length;

    }
</script>
    </head>

<body>
    <button onClick="newElement();">Add Element</button>
    <button onClick="updateStats();">Update Stats</button>

<header id="wrapper">
    <div>
        Div 1
    </div>
</header>

<h3>querySelector Before</h3>
<p>Type:<span id="queryB"></span></p>
<p>Length:<span id="queryBL"></span></p>
<h3>After</h3>
<p>Type:<span id="queryA"></span></p>
<p>Length:<span id="queryAL"></span></p>
<hr>
<h3>getElementByTagName Before</h3>
<p>Type:<span id="getB"></span></p>
<p>Length:<span id="getBL"></span></p>
<h3>After</h3>
<p>Type:<span id="getA"></span></p>
<p>Length:<span id="getAl"></span></p>

<script>
    q = document.querySelectorAll('div')
    g = document.getElementsByTagName('div')
    
    document.getElementById('queryB').innerHTML = q;
    document.getElementById('queryBL').innerHTML = q.length;
    document.getElementById('getB').innerHTML = g;
    document.getElementById('getBL').innerHTML = g.length;

</script>
</body>


  </html>

I have searched Google and cant find the answer, moving the script to the bottom of the page didnt work.


Solution

  • Line 15 you get incorect id:
    Try this: document.getElementById('getAl').innerHTML = g.length;