Home > Net >  Set different backgroundcolor on numbers from an array in DOM Javascript
Set different backgroundcolor on numbers from an array in DOM Javascript

Time:10-17

Im stucked in how to create this below;

1.Create an array with 10 numbers from 0 to 360 2. write out in DOM in an element of choice 3.Set the background color of each number, by using the number of HUE in (hue, saturation, lightness)

//1
let nummers = [1,26,320,45,56,216,78,88,119,100]
  console.log(nummers)

//2
let parNummer = document.querySelector('.nummer')

//3

function brightness(){

    const map1 = nummers.map(x => {
        const skrivUt = document.getElementById('output2')
        nummers.forEach(nummer => {
            if (nummer === 119) skrivUt.style.background = `hsl(${nummer}, 100%, 50%)` 
        })
        skrivUt.innerText = nummers
    });
brightness()

CodePudding user response:

You're heading in the right direction.

  1. It's not clear if you need to create the element in JS and append it to the DOM, or hardcode it in the HTML, and then pick it up. If it's the former you need to create the element first, and then append it.

  2. You need to make one loop over the numbers rather than use a nested loop. For each element in the array create a new element (I've used a div), set its background colour, and its text content, and then append it to the container.

(Note: I've used a bit of CSS styling to make the example pretty but you can ignore that.)

const numbers = [1, 26, 320, 45, 56, 216, 78, 88, 119, 100];

// Create a containing element
const container = document.createElement('div');
container.className = 'container';

// Append it to the DOM
document.body.append(container);

// Loop over the numbers array
// For each number set the background color, and the
// text content, and then append it to the container
for (let num of numbers) {
  const el = document.createElement('div');
  el.className = 'number';
  el.style.backgroundColor = `hsl(${num}, 100%, 50%)`;
  el.textContent = num;
  container.append(el);
}
.container { display: grid; grid-template-columns: repeat(5, 50px); gap: 0.25em; }
.number { display: flex; justify-content: center; align-items: center; width: 50px; height: 50px; font-size: 1.2em;}

  • Related