0

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

  • 2
    because `getElementByClassName` method doesn't exist in Javascript. there is only a `getElementsByClassName` method which return a collection of elements, event if this collection have only one element – Mister Jojo Mar 07 '23 at 14:01

3 Answers3

0

The issue with your code is that getElementByClassName should be getElementsByClassName (note the "s" in Elements). This is because getElementsByClassName returns a collection of all elements in the document that has the specified class name.

const board = document.createElement('div');
const mainContainer = document.getElementsByClassName('container')[0];
board.className = 'blah';
mainContainer.appendChild(board);
Karim
  • 1,004
  • 8
  • 18
0

getElementsByClassName returns an HTML collection, so you just give mainContainer with index do you want.

mainContainer[0].appendChild(board);

Full code :

const board = document.createElement('div');
const mainContainer = document.getElementsByClassName('container');
board.className = 'blah';
mainContainer[0].appendChild(board);
Jordy
  • 1,802
  • 2
  • 6
  • 25
0

You have a syntax error getElementByClassName should be getElementsByClassName however assuming that issue is a copy/paste error; your mainContainer 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:

for (let i = 0; i < mainContainer.length; i++) {
    const board = document.createElement('div');
    board.className = 'blah';
    mainContainer[i].appendChild(board);
}
Mark Schultheiss
  • 32,614
  • 12
  • 69
  • 100