javascriptnullappendgetelementbyidgetelementsbyclassname

Javascript method getElementsByClassName or getElementByID returning null


This seems so simple, but I cannot seem to wrap my head around what it is that I am doing wrong.

I'm merely trying to create a system of tags by passing an array of objects into the html of a div within the dom using vanilla javascript.

I have some very simple html

<html lang="en">
  <head></head>
  <body>
    <div class="tagtype"></div>
    <script src="index.js"></script>
  </body>
</html>

And I have some simple javascript I am attempting to populate within the tagtype div.

const tags = ["One", "Two", "Three", "Four", "Five", "Six", "Seven"]
var varName = document.getElementsByClassName("tagtype");
function generateTags () {
    for(var i = 0; i < tags.length; i++) {
    var tagTypes = document.createElement("div");
        tagTypes.innerHTML = tags[i];
        tagTypes.classList.add(tags[i]);
        varName.append(tagTypes);
    }
}
generateTags();

In most cases I've found when digging into this, people explain that the code is run before the DOM element exists, so I tried placing the script tags before closing the body. I have also tried passing the for loop from within and outside of a function generateTags.
I have tried variations on the class as an ID by passing the getElementById() method against a div with id tagtype.
I have even come across a discussion suggesting I need to make the tagtype variable the first in its 'array'.
However despite these I cannot seem to grab the tagtype div within the DOM and populate the tags inside of the element.
I usually get some variation of tagtype returns null or undefined or tagtype.append is not a function.

Any advice?


Solution

  • the code is run before the dom element exists

    This is not the case, since your script tag is placed under the element you wish to modify.

    tagtype.append is not a function

    There's your answer. getElementsByClassName doesn't return an Element. It returns a HTMLCollection. Element.append is a method. HTMLCollection.append is not.

    Instead of doing varName.append(tagTypes), you should reference an element within the list and append to that. In this case, do varName[0].append(tagTypes).

    const tags = ["One", "Two", "Three", "Four", "Five", "Six", "Seven"]
    var varName = document.getElementsByClassName("tagtype");
    function generateTags () {
        for(var i = 0; i < tags.length; i++) {
        var tagTypes = document.createElement("div");
            tagTypes.innerHTML = tags[i];
            tagTypes.classList.add(tags[i]);
            varName[0].append(tagTypes);
        }
    }
    generateTags();
    <html lang="en">
      <head></head>
      <body>
        <div class="tagtype"></div>
        <script src="index.js"></script>
      </body>
    </html>