Why HTMLCollection is Live?

Hi, in this post I’m going to explain you how the Live definition works in the DOM.

If you want to know more about HTMLCollection vs NodeList you can click on the link.

HTMLCollection is consider LIVE that means if we are updating our web application and we have a variable that holding the HTMLCollection; for example if we add another element to that collection then the variable also will change or will be update with counting the new element that was added.

Let’s see the code:

HTML

<!DOCTYPE html>

<!-- this comment is a child of the document -->

<html lang="en">

    <head>
        <meta charset="UTF-8">
        <title>Nodelists Vs HTMLCollections</title>
        <meta name="viewport" content="width=device-width">
        <link rel="stylesheet" href="styles.css">
        <!-- This comment is a child element of the head element -->
    </head>

    <!-- I'm a comment that is a child of the html element -->

    <body>
        <h1>Heading</h1>

        <main id="main">

            <section id="a" class="sections" name="theSections">
                <p>Section A has five paragraphs. Each paragraph is a Child Element Node of the section Element Node. The text inside each paragraph tag is a Text Node.</p>
                <p>Eligendi porro fuga velit libero suscipit temporibus repellendus facilis molestias, eaque modi reiciendis aut incidunt voluptas.</p>
                <p>Saepe autem voluptates, quibusdam, quis provident hic, ab tenetur placeat numquam maxime, amet sunt rerum. Nemo distinctio alias</p>
                <p>Excepturi, iure, unde. Eos fugiat quos aperiam fuga minima esse quisquam corrupti dolore tempora ad ex nulla, explicabo, fugi</p>
                <p>Necessitatibus officiis, dolosumenda repellat voluptatem aut et! Placeat perferendis reprehenderit, cumque iste tempore aut.</p>
            </section>
            
            <section id="b" class="sections" name="theSections">
                <p>Section B has four paragraphs. Lorem ipsum dolor sit amet, us beatae vel illum mollitia fugiat modi aperiam excepturi natus quisquam ab molestias, expsoluta.</p>
                <p>Eligendi porro fuga velit libero suscipit temporibus repellendus facilis molestias, eaque modi reiciendis aut incidunt voluptas saepe assumenda omnis aperixplicabo.</p>
                <p>Saepe autem voluptates, quibusdam, quis pro. Nemo distinctio alias inventore rem doloribus, nostrum magni natus illo reprehenderit provident pariatur explicabo officia.</p>
                <p>Excepturi, iure, unde. Eos fugiat quos aperiam fuga minima esse quisquam corrupti dolore tempora ad ex nulla, explicabo, fugit reicitur quo totam laborum!</p>
            </section>

            <!-- I'm a comment node after the two sections -->
        </main>

        <script src="script.js"></script>

    </body>
</html>
       

This is how the HTML looks like in the browser:

Cool!, now let see the Javascript logic; If we want a HTMLCollection format then we can use different types of ways, such as:

  • .children property
  • .getElementsByClassName(‘class’) method
  • .getElementsByTagName(‘p’) method
  • .forms property
  • .getElementsByTagNamesNS(‘xml’) method

Example:

// Getting the main element
let main = document.getElementById('main');

let elementsByClass = document.getElementsByClassName('sections'); // HTMLCollection LIVE
let elementsByTag = document.getElementsByTagName('section'); // HTMLCollection LIVE
let childrenCollection = main.children; // HTMLCollection LIVE

console.log('elementsByClass --->', elementsByClass);
console.log('elementsByTag --->', elementsByTag);
console.log('childrenCollection --->', childrenCollection);

Result:

Nice!, now we know what methods are the ones that return us HTMLCollection then as the definition said: that the HTMLCollection act as Live, so, in this case if we add another element to “main” element then the HTMLCollection will be updated with the new added element, look:

If we see the length of our actual HTMLCollection before that we insert the new element then will be like this:

// Getting the main element
let main = document.getElementById('main');

let elementsByClass = document.getElementsByClassName('sections'); // HTMLCollection LIVE
let elementsByTag = document.getElementsByTagName('section'); // HTMLCollection LIVE
let childrenCollection = main.children; // HTMLCollection LIVE

console.log('elementsByClass --BEFORE INSERT-->', elementsByClass.length);
console.log('elementsByTag --BEFORE INSERT-->', elementsByTag.length);
console.log('childrenCollection --BEFORE INSERT-->', childrenCollection.length);

Result:

Nice next step is add the new element to the HTMLCollection in this case my element is <section id=”c” class=”sections”>Hi there!</section> check the code:

// Getting the main element
let main = document.getElementById('main');

let elementsByClass = document.getElementsByClassName('sections'); // HTMLCollection LIVE
let elementsByTag = document.getElementsByTagName('section'); // HTMLCollection LIVE
let childrenCollection = main.children; // HTMLCollection LIVE

// Adding new section element to "main"
main.innerHTML += '<section id="c" class="sections">Hi there!</section>';

// Printing the length of the HTMLCollection after insert the section element
console.log('elementsByClass --AFTER INSERT-->', elementsByClass.length);
console.log('elementsByTag --AFTER INSERT-->', elementsByTag.length);
console.log('childrenCollection --AFTER INSERT-->', childrenCollection.length);

Result: And this is why the HTMLCollection is LIVE because when we add a new element to the DOM this is reflected instantly in the HTMLCollection and the length will be 3:

By Cristina Rojas.