Karle Karle - 15 days ago 5
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?

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

Answer

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.

Comments