Q:

JS creating divs with a for loop inside container

I am trying to create a number of divs inside a container, but i cant figure out how to nest the created ones within the main container. Is it also possible or better to create the container before in the html? 
JS
function createDiv(numberOfDivs) {
  var i = 0;
  var newElement = [];
  var mainContainer = document.createElement('div');

  mainContainer.innerHTML = 'MAIN CONTAINER';
  mainContainer.className = 'main';
  document.body.appendChild(mainContainer);

  for (i; i < numberOfDivs; i++) {
    newElement[i] = document.createElement('div');
    newElement[i].style.backgroundColor = '#' + Math.floor(Math.random() * 16777215).toString(16);
    newElement[i].className = 'box';
    newElement[i].id = (i + 1);
    newElement[i].textContent = 'this is div number: ' + (i + 1);
    document.body.appendChild(newElement[i]);
  }
};

createDiv(10);

A:

Yes, you can create the container in the html ahead of time, as others have suggested.  Then you can nest your divs inside that container.
<html><body><div id="mainContainer" ></div></body></html>

As others suggested you can apply the necessary css to make it hidden if necessary until you want it visible.
Then javascript to nest divs inside mainContainer:
function createDiv(numberOfDivs){
    var $mainContainer = $("#mainContainer");
    for (i; i < numberOfDivs; i++) {
        var newDiv = $("<div class='box' />");

        //...you can add whatever attributes to the div that you want...

        $mainContainer.append(newDiv);
    }
}

