var node = document.createElement("li");
node.appendChild(document.createTextNode("item"));
list = document.getElementsByClassName("itemList");
list.appendChild(node);
I’m reworking a JS project that I had trouble with in the past and this is giving me quite the hassle. My inspector keeps giving me errors that appendChild is “not a function” or “cannot call method ‘appendChild’ of null”.
Even if I copy an example from somewhere else, I get the same error. This is just a test, but eventually I wan’t to be able to append array items to an unordered shopping list.
I haven’t included any event handlers yet. Aside from the array objects and a couple functions I used to calculate the price total, that’s all that I have in my script file. I tried starting over from scratch just so I could focus the problem, but it seems to just be that one appendChild line.
I tried wrapping everything in my script document and also just wrapping the the DOM calls. For both, everything else on the page showed as normal, but I’m still getting errors saying that appendChild(node) isn’t a function.
There are a few choices - you can iterate over the pseudoarray returned by getElementsByClassName - I like querySelector and querySelectorAll because they support CSS selector expressions e.g. document.querySelector(".itemList").appendChild(node)