Search code examples
appendchild

document.getElementsBy..().appendChild is not a function error


i have been trying to create a div inside my DOM every time i press the button yet it says appendChild is not a function sorry for the rude code but thats where i am at the moment.

var btn = document.getElementsByTagName('button')[0];

function crtRow(){
   var newDiv = document.createElement('div');
   newDiv.className = 'row';
   document.getElementsByClassName('container').appendChild(newDiv);
   document.body.appendChild(container);
}

btn.addEventListener('click', crtRow)

Solution

  • In your example appendChild is trying to be executed with HTML Collection, which it can't. You need to specify index for html collection document.getElementsByClassName('container')[0]

    Also, then you will see another error for this line of code document.body.appendChild(container);. That's because you didn't define a variable called as container. It will try to append undefined to the body.