skip to Main Content

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


  1. 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);
    
    Login or Signup to reply.
  2. 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);
    
    Login or Signup to reply.
  3. 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);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search