Some DOM confusion

I am new to all this DOM stuff, so now I am trying to render some elements with vanilla JS for the learning purposes.

Right now I am trying to render bunch of div elements inside the section.
It described in the comments(lower part of code, BLOCK3).

I am trying to achieve this with some looping.

For some reason, I am rendering only last div, not all four of them.

I guess I don’t have understanding how this should work: I think I messed up with constants, or with assigning values to variables, or with understanding how createElement works - too much possible places where mistake could be.

Thus, need some direction.

const fullWidth = 'width: 100%;';
const borderForTesting = 'border: 1px solid black;';

adding mainContainer inside the body, giving it some style*/

const mainContainer = document.createElement('div');
mainContainer.className = "main-container";
// = '100%'
// = '100vw';
// = '#A1A1A1';
//console.log(mainContainer); = 'width:100%; height:100vw; background-color:#A1A1A1'
document.body.insertBefore(mainContainer, document.body.firstChild);

adding section with heading and description*/
const heroSection = document.createElement('section');
const mainHeading = document.createElement('h1');
mainHeading.innerText = 'First DOM sandbox';
const mainDescription = document.createElement('p');
mainDescription.innerText = 'messing around DOM in order to get practice';


for (let child of heroSection.children) { = 'text-align:center; font-family:Verdana';
// console.log(typeof(heroSection.children));//object

3.1 >>> add 2nd section; is should be flex-containter
3.2 >>>inside it add 4 divs
each 100% width
each has different h2 heading; also color-coded differently

// 3.1
const flexSection = document.createElement('section'); = `${fullWidth} display: flex`;
// console.log(;

// 3.2
const divFlexItem = document.createElement('div');
const divHeading = document.createElement('h2');
const colorCode = [
const divHeadingsText = [
    'Clock sandbox',
    'Input/output sandbox',
    'Some sandbox',
    'Last sandbox'
// console.log(colorCode, divHeadings);

for (let idx = 0; idx < colorCode.length; idx++) {
    let newDiv = divFlexItem;
    // console.log(idx)
    // console.log(newDiv) = `background-color: ${colorCode[idx]}; ${fullWidth}`;
    let newDivHeading = divHeading;
    //TODO - make this css for headings variable = `text-align:center; font-family:Verdana`;
    newDivHeading.innerText = divHeadingsText[idx];

Nevermind, I was able to fix this:
removed this:

And rewrote loop a little bit.

I guess I still have bunch of questions, but I’ll figure it out with more research.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.