Change the background color of numbers in an array using DOM manipulation in JavaScript

Can someone assist me with the following task:

1. Generate an array containing 10 numbers ranging from 0 to 360. 2. Display these numbers on the DOM within a chosen element. 3. Adjust the background color of each number based on its HUE value in (hue, saturation, lightness).

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

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

//3
function adjustColor(){

    const mappedNumbers = numbers.map(x => {
        const outputElement = document.getElementById('output2')
        numbers.forEach(num => {
            if (num === 119) outputElement.style.background = `hsl(${num}, 100%, 50%)` 
        })
        outputElement.innerText = numbers
    });
}
adjustColor()

Answer №1

You're on the right track.

  1. It's important to determine if you should dynamically create the element using JavaScript and add it to the DOM or manually code it in the HTML and then retrieve it. If you opt for the former, remember to create the element first before appending it.

  2. Avoid using nested loops; instead, use a single loop when iterating over numbers. Create a new element (such as a div) for each item in the array, set its background color and text content, then append it to the designated container.

(Please disregard the CSS styling used for aesthetics in this example.)

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

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

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

// Iterate through the numbers array
// Set the background color and text content for each number
// 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;}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the reason for Bower consistently choosing to download the Angular version 1.5.9-build.5086+sha...?

Struggling to manage my front end dependencies using bower.json. No matter how I specify the version of Angular in bower, a different version is downloaded every time. The issue is that many functionalities in my code rely on previous versions of Angular, ...

Retrieve the child DIV element within its sibling without using an identifier

I have a setup similar to the following: <div class="panel panel-primary"> <div class="panel-heading"> <h3 class="panel-title">Tiger128 (v2)</h3> </div> <div class="panel-body"> <inp ...

Having trouble with Ajax.updater?

I am a JavaScript newcomer and currently facing an issue with prototypes. I am attempting to update sample.jsp using Ajax.updater after it is loaded, but for some reason, it's not working. Here is the source code of sample.jsp: <%@page contentTyp ...

How can we convert milliseconds to the corresponding date and time zone in Java?

1)I am trying to determine the user's timezone and current time using the following code snippets: Calendar currentdate1 = Calendar.getInstance(); TimeZone tz = Calendar.getInstance().getTimeZone(); System.out.println("time zone"+tz); System.out.pri ...

Contrast arrays and eliminate values that do not match

$scope.territories = [ { name : "One"}, { name : "Two"}, { name : "Three"}, { name : "India"}, { name : "Japan"}, { name : "China"} ]; $scope.tempTerritories = [ { name : "One"}, { name : "Two"}, { name : "global"}, ]; ...

Simplified React conditional rendering made easy

Currently, I am utilizing React 16 with Material-Ui components. In my root component, I have a requirement to load a tab and a view conditionally based on a property. Although I have managed to implement this functionality, the code appears quite messy a ...

What is the process for generating an array of objects using two separate arrays?

Is there a way to efficiently merge two arrays of varying lengths, with the number of items in each array being dynamically determined? I want to combine these arrays to create finalArray as the output. How can this be achieved? My goal is to append each ...

Implementing CSS styles according to user preferences. Switching between dark mode and light mode based on subscription

Is there a way to dynamically change CSS property values based on user interaction, such as toggling between dark mode and light mode? I am currently exploring the option of setting up a subscription to track these changes, but I want to know how I can act ...

Is there a way to stop vue-panZoom from functioning temporarily?

I am working with a Grid that includes the use of vue-panZoom. Within the Grid, there is a section that utilizes vue-draggable-resizable, similar to what is depicted in the image below: Image When I drag the gray square (vue-draggable-resizable), the bl ...

Error message: A boolean type cannot be used as a function in the fullcalendar ajax call

I have successfully implemented a fullcalendar into my app and have added a method to filter results by user: function filterEventsByProvider(selected_provider) { $('#calendar').fullCalendar('removeEvents'); $('#calendar&a ...

Ways to combine X and Y velocities into a single velocity

Is there a way to combine the X and Y Velocity into a single Velocity without considering the angle? var velocityX = some value; var velocityY = some value; // Need to convert both X and Y velocities into one combined velocity ...

Using CSS, center a div element both vertically and horizontally, and position the footer at the bottom of the page

I am encountering some unexpected behavior for a task that I thought would be simple. I have two main objectives in mind. Firstly, I want the footer to be displayed at the bottom of the page as an actual footer. Secondly, I need the div with the ".center-d ...

Dynamic Loading of Multiple Scripts on a Webpage with Dependencies in JavaScript

I am currently working on developing a page constructor entirely using JavaScript. The issue arises when I dynamically add two scripts to the page that are dependent on each other. For instance, in this scenario, I am loading jQuery from a CDN, and in the ...

Issue in Jquery: Unable to load the corresponding pages when toggling the checkbox on and off

I am facing an issue with a checkbox and calling different php pages based on the status of the checkbox. Currently, the code works only for checked checkboxes. I'm not sure why it's not working for unchecked checkboxes as well. <script type ...

Python's alternative code to MATLAB's vec2mat

Currently, I am in the process of converting a piece of MATLAB code to Python. The code is not very pythonic at the moment, but I plan on refining it later. In the original MATLAB script, there is a function called vec2mat from the Communications systems ...

Exploring ways to extract HREF using Selenium in combination with Node JS

I am having trouble extracting the hrefs from my web element using .getAttribute("href"). It works fine when applied to a single variable, but not when looping through my array. const {Builder, By, Key, until} = require('selenium-webdriver'); (a ...

Why do I keep getting undefined when I use React.useContext()?

I'm currently using Next.js and React, employing react hooks along with context to manage state within my application. Unfortunately, I've encountered a perplexing issue where React.useContext() is returning undefined even though I am certain tha ...

What's the best way to ensure a div's height and width are equal when implementing responsive design?

I am currently working on a responsive design and facing challenges in making div's height and width equal. Initially, I set the div's width as a percentage and height as auto, but this caused the divs to not display properly. To resolve this iss ...

Converting JSON to an array using Python

Need help converting this JSON excerpt using Python, changing the list into an array. Anyone know the best practice or a clever method to achieve this? { "date": "2020-10-19", "aaa": "123", "bbb": &qu ...

Combining two sets of elements in Java to form a Json using Jackson

Is there a way to combine two List of objects retrieved from the database into a single object in order to serialize with Jackson and deserialize in the view? ObjectMapper mapper = new ObjectMapper(); jsonTutorias = mapper.writeValueAsString(tuto ...