Home > Software design >  Dynamically append the element through JavaScript Dom
Dynamically append the element through JavaScript Dom

Time:06-12

Hers's question which I need answer

Exercises: Level 1 Question 1

I tried to append the child dynamically and get the result vertical not in the compact manner as you will see in the question output when you go to the link

let hh = document.querySelector('h1')
hh.style.textAlign = 'center'
let hh1 = document.querySelector('h2')
hh1.style.textAlign = 'center'
let hh2 = document.querySelector('h3')
hh2.style.textAlign = 'center'

for (i = 0; i <= 100; i  ) {

  let p1 = document.createElement('div');

  {
    if (i % 2 == 0) {

      p1.className = 'Container'
      p1.style.fontSize = '25px'
      p1.style.backgroundColor = '#91E537'
      p1.textContent = i;
      p1.style.padding = '55px'
      p1.style.margin = '1px'
      p1.style.textAlign = 'center'
      p1.style.width = '20px'
      document.body.appendChild(p1);
    } else {
      p1.className = 'Container'
      p1.style.fontSize = '25px'
      p1.textContent = i;
      p1.style.backgroundColor = '#E5D037'
      p1.style.padding = '55px'
      p1.style.margin = '1px'
      p1.style.textAlign = 'center'
      p1.style.width = '20px'
      document.body.appendChild(p1);
    }
  }
  if (i >= 2) {
    let flag = 0;
    for (j = 2; j <= i / 2; j  ) {
      if (i % j == 0) {
        flag = 1;
        break;
      }
    }
    
    if (flag == 0) {
      p1.className = 'Container'
      p1.style.fontSize = '25px'
      p1.style.backgroundColor = '#E55137'
      p1.textContent = i;
      p1.style.padding = '55px'
      p1.style.margin = '1px'
      p1.style.textAlign = 'center'
      p1.style.width = '20px'
      document.body.appendChild(p1);

    }
  }
}
<h1>Number Generator</h1>
<h2>30 days of JavaScript</h2>
<h3>Author:ABC</h3>
<div ></div>

You can see the code of both HTML and javascript above!!! Do help with the code where I can easily append the data, and don't use box elements I need simple code for this. I tried to do it with a few HTML styles but it didn't help me, also using insert-adjacent text also didn't work. Try to make changes only on javascript code, not HTML,if it's possible else make minimum changes on HTML

I am using HTML5 AND CSS3

CodePudding user response:

The idea here is to create a container for all of the blocks and set the display style attribute of this container to flex, style.flewrap to wrap and you can control how many blocks you want per line using style.width attribute.
After creating this element you would want to append to it your dynamically created blocks like p2.appendchild(p1);
Here is the code :

let p2 = document.createElement('div');
p2.className= 'p2';
p2.style.display = 'flex';
p2.style.flexwrap = 'wrap';
p2.style.width = '800px'
for (i = 0; i <= 101; i  ) {
    ...
    for every document.body.append(p1); --> p2.append(p1);
    ...
}
document.body.appendChild(p2);

CodePudding user response:

Rather than adding lots of inline style attributes to all the generate elements some simple CSS can be applied to the parent (container) and thus the children and then use Javascript to assign the classes to the elements based upon the given criteria of odd/even & prime. The comments throughout the code ought to help

// helper function to create basic DOM element with attributes
const node=( type='div', attr={} )=>{
  let n = document.createElement(type);
  Object.keys( attr ).forEach( a=>n.setAttribute( a, attr[a] ) );
  return n;
};

// utility to test if a number is a "Prime Number"
const isprime=( n=0 )=>{
  for( let i = 2; i < n; i   ) {
    if( n % i === 0 ) return false;
  }
  return n > 1;
};

// generate between these numbers
const iStart=1;
const iEnd=100;

// HTML container
const results = document.querySelector('#results');

// iterate through number range and add new DIV for each number
for( let i = iStart; i<=iEnd; i   ) {
  // calculate the className to assign
  let cn=i % 2 === 0 ? 'even' : 'odd';
  if( isprime( i ) ) cn='prime';
  
  // create the DIV
  let div=node( 'div', { 'class':cn, 'data-id':i } );
  
  // append to output container
  results.appendChild( div );
}



// generate Page headers before results / output
let headers={
  h1:'Number Generator',
  h2:'30 days of Javascript',
  h3:'Geronimo Bogtrotter III'
};
// iterate over the keys/properties of the object and create 
// a new header for each using the value assigned within the object.
Object.keys( headers ).forEach( prop=>{
  let n=node( prop );
      n.textContent=headers[ prop ];

  // add the new header before the numbers grid
  document.body.insertBefore( n, results );
});
/*
  Some simple variables to help with layout.
  Change here to modify displayed grid.
*/
:root{
  --width:600px;
  --m:0.25rem;
  --r:0.35rem;
  --wh:calc( calc( var( --width ) / 5 ) - calc( var( --m ) * 4 ) );
}


body{
  font-family:monospace;
  padding:0;
  margin:0;
}
#results {
  width: var(--width);
  min-height: var(--width);
  float: none;
  margin: 1rem auto;
  font-family:fantasy;
}
#results > div {
  width: var( --wh );
  height: var( --wh );
  border: 1px solid black;
  border-radius:var(--r);
  margin: var(--m);
  display: inline-block;
  cursor:pointer;
}


/*
  Use the pseudo element :after to 
  display the number of the square.
  
  This uses the `data-id` attribute
  assigned within Javascript.
*/
#results>div:after {
  display:flex;
  flex-direction:column;
  justify-content:center;
  align-content:center;
  align-items:center;
  flex:1;
  margin:auto;
  content: attr(data-id);
  color:black;
  text-shadow:0 0 15px rgba(255,255,255,1);
  height:100px;
}

/*
  modify the display for certain colours
  to aid clarity
*/
#results>div.odd:after{
  text-shadow:0 0 15px rgba(0,0,0,1);
}
#results>div.prime:after{
  text-shadow:0 0 15px rgba(0,0,0,1);
  color:white;
}

/*
  The basic 3 colours to suit the odd/even/prime
  status of each square.
*/
.even {
  background: green;
}
.odd {
  background: yellow
}
.prime {
  background: red
}


h1,h2,h3{
  text-align:center;
}
<div id='results'></div>

  • Related