Karle Karle - 4 months ago 34
HTML Question

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?


function createDiv(numberOfDivs) {
var i = 0;
var newElement = [];
var mainContainer = document.createElement('div');

mainContainer.innerHTML = 'MAIN CONTAINER';
mainContainer.className = 'main';

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);



If you can, you should create them without using javascript. Otherwise, you are appending the new elements to document.body. Just change that to be mainContainer.