Search code examples
javascriptjqueryhtmlappendchild

appendChild() is not a function


I tried a little pen on codepen.io (here is mine <3),

Here is the code:

  var body = $('body');
  var container = document.getElementsByTagName("container");

  var tileTab = new Array(); 

  var windowWidth = window.innerWidth;
  var windowHeight = window.innerHeight;

  var nbTileWidth = Math.floor(windowWidth / 50) - 1;
  var nbTileHeight = Math.floor(windowHeight / 50) - 1;
  var x = 0;

  for(var i = 0; i < nbTileHeight; i++){

    var row = document.createElement("div");

    for(var j = 0; j < nbTileWidth; j++){

      tileTab[x] = document.createElement("div");
      row.appendChild(tileTab[x]);
      tileTab[x].className = "tile";
      x++;

    }
    container.appendChild(row);
    row.className = "row";
  }
  body.appendChild(container);

This pen is available here : codepen

Console return me

container.appendChild is not a function

I tried it with jQuery but it's the same :/.

Sorry to post this, it seems to be a basic issue but now i don't know what's wrong here. Ty in advance!


Solution

  • Replace these lines:

    var body = $('body');
    var container = document.getElementsByTagName("container");
    

    with these:

    var body = document.body;
    var container = document.querySelector('.container');