I am using the following code in JavaScript to insert a div with class = "blah" inside a main div with class = "container" (the main div is created with HTML) but something goes wrong.
const board = document.createElement('div');
const mainContainer = document.getElementByClassName('container');
board.className = 'blah';
mainContainer.appendChild(board);
The error I get is "Uncaught TypeError: mainContainer.appendChild is not a function". What am I missing?
Thank You for the help
3
Answers
The issue with your code is that
getElementByClassName
should begetElementsByClassName
(note the "s" in Elements). This is because getElementsByClassName returns a collection of all elements in the document that has the specified class name.getElementsByClassName
returns an HTML collection, so you just givemainContainer
with index do you want.Full code :
You have a syntax error
getElementByClassName
should begetElementsByClassName
however assuming that issue is a copy/paste error; yourmainContainer
is not singular even if there is one; it is "an array-like object of all child elements which have all of the given class name(s)." So you need to iterate over that list to append a child to each one.example: