Set a unique class for several elements depending on a given condition

Is there a way to assign a color class based on the element's value without looping through all elements?

Check out my jsfiddle

HTML

<div>
     <ul>
         <li class="MyScore">90</li>
         <li class="MyScore">82</li>
         <li class="MyScore">77</li>
         <li class="MyScore">66</li>
         <li class="MyScore">62</li>
         <li class="MyScore">50</li>
         <li class="MyScore">42</li>
     <ul>
    </div>

CSS

.good{
        background-color: green;
    }
    .okay{
        background-color: yellow;
    }
    .bad{
        background-color: red;
    }

JS

function scoreColor(score){
        var score = document.querySelector('.MyScore').innerHTML;
        var scoreColor = document.querySelector('.MyScore');
        
        if(score > 85){
            scoreColor.className + ' good';
            console.log('good');
        } else if(score > 65 && score < 85 ){
            scoreColor.className + ' okay';
            console.log('okay');
        } else {
            scoreColor.className + ' bad';
            console.log('bad');
        }
    }
    scoreColor();

Thanks

Answer №1

Take a look at this code snippet and check out the comments provided (fiddle):

 function highlightScores() {
     var scores = document.querySelectorAll('.MyScore'); // select all elements with .Myscore

     Array.prototype.forEach.call(scores, function (item) { // loop through the elements

         var score = parseInt(item.innerText, 10); // extract and parse the value from text

         if (score > 85) {
             item.classList.add('good'); // add 'good' to element's classList
             console.log('good');

         } else if (score > 65 && score < 85) {
             item.classList.add('ok'); // add 'ok' to element's classList
             console.log('ok');
         } else {
             item.classList.add('bad'); // add 'bad' to element's classList
             console.log('bad');
         }
     });


 }
 highlightScores();

Answer №2

Here's a little something to try out:

let scores = document.querySelectorAll('.MyScore');
for (let x of Array.from(scores)) {
    let points = parseInt(x.innerHTML);
    if (points > 85){
        x.className = 'excellent';
    } else if (points > 65 && points < 85){
        x.className = 'good';
    } else {
        x.className = 'fair';
    }
}

The querySelectorAll method gathers all elements that match the specified criteria, and using Array.from helps arrange them into an array for easier handling.

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

Conceal elements on smaller screens using the Bootstrap 5 grid system

I'm facing a design issue with my layout - it looks perfect on larger screens but when viewed on mobile devices, the columns stack vertically instead of horizontally. Essentially, I want to hide the first and second last column on small screens and r ...

What's the best method for uploading a file to AWS S3: POST or PUT requests?

Could you please provide insights on the advantages and disadvantages of utilizing POST versus PUT requests for uploading a file to Amazon Web Services S3? Although I have come across some relevant discussions on platforms like StackOverflow, such as this ...

Tips for dynamically updating the div class based on the model's value

How can I dynamically change the CSS class of a bootstrap element based on a value? I would like to display a div in green if the value is "OK" and red otherwise. If status = "OK", it should look like this: <div class="small-box bg-green">, else < ...

Retrieve a Google map using Ajax in a PHP script

I'm attempting to display a google map on my homepage using the following function: function addressCode(id, concatenatedToShowInMap) { var geocoder; var map; geocoder = new google.maps.Geocoder(); ...

Issue: The function (0, react__WEBPACK_IMPORTED_MODULE_1__.useActionState) is not recognized as a valid function or its output is not iterable

I found a great example of using useActionState at this source. Currently, I am implementing it in my project with Next.js and TypeScript. app/page.tsx: "use client"; import { useActionState } from "react"; import { createUser } from ...

Continuous front-end promise awaiting response from back-end Node.js function

Currently, I am working on a basic React frontend where I need to fetch some data from my backend API powered by Node.js. This backend API calls an external API to get the required data. Although I have verified that the data is fetched successfully on the ...

Creating an infinite SVG animation loop using JavaScript

elem = document.querySelectorAll("path"); function task(i) { setTimeout(function() { elem[i].animate({fill: 'green'}, { // timing options duration: 150, iterations: 1 }); }, 150*i); } for(var i=0;i<8;i++){ task(i); } < ...

Tips on duplicating an object within a React state without using references

In my React application, I have a state that contains several objects. I need to make a copy of the c: "value" field from the initial state before it gets replaced by the input value from e.target.value. The purpose behind this is to ensure that ...

Utilizing AJAX response to update the current URL in a Spring MVC application - A step-by-step guide

In my ongoing project using Spring MVC, the homepage features two input fields of String type. However, the regNo field accepts numbers as input. If a user enters a regNo, it should be directed to a specific method in the controller. On the other hand, if ...

What could be causing the change event to be triggered in a v-text-field when I press enter, despite not making any changes?

How come the @change event triggers in a v-text-field when I press enter, even if I haven't made any changes? HTML <div id="app"> <v-app> <v-content> <v-container> <v-text-field @change=" ...

Adjusting the content of a single text box by typing in another

Is it feasible to automatically convert a Nepali date input in one textbox into an English date and display it in another textbox without any page refresh? I have a PHP function that can translate dates between Nepali and English, and I want it to execute ...

Manipulating background scrolling using jQuery

I had a vision of creating a logo with PNG transparency and a scrolling background that would give the appearance of being made in Flash. To achieve this effect, I utilized the jquery.backgroundPosition.js plugin for enabling background scrolling. Here is ...

The CSS is not functioning properly on the admin page of a Django application hosted on AWS

After following a tutorial on setting up Python Django on AWS Elastic Beanstalk, everything seemed to be working fine except for the CSS on the administration page. I tried troubleshooting by looking at various Stack Overflow threads like Default Django 1 ...

Creating a cron job that can be rescheduled using Node.js

I am utilizing the node-schedule package from GitHub to create cron jobs. While I have successfully created a basic scheduler, my goal is to make it reschedulable. Within my application, users can initiate tasks for specific dates. This can be easily achi ...

What is the best way to ensure that each service call to my controller is completed before proceeding to the next one within a loop in Angular?

Calling an Angular service can be done like this: this.webService.add(id) .subscribe(result => { // perform required actions }, error => { // handle errors }); // Service Definition add(id: number): Observable < any > { retu ...

Creating a task management system using HTML, CSS, and JavaScript that utilizes local

I have been extensively researching how to create a to-do list using JavaScript with local storage, but unfortunately, I have not been able to find exactly what I am looking for. Is there a way for me to set up a to-do list and input data before actually ...

What is the process for comparing two objects in TypeScript?

There is a unique class named tax. export class tax { private _id: string; private _name: string; private _percentage: number; constructor(id: string = "", taxName: string = "", percentage: number = 0) { thi ...

How come I am unable to connect my CSS to my EJS files?

Having difficulty linking my css files to my ejs files. Using a standard node.js/express setup, I'm attempting to connect my main.css file from the public/css directory to my index.ejs file in views. The html and routing are functioning correctly. Ple ...

Having trouble combining different styles with Material-ui and Radium?

Trying to integrate Radium with Material-ui has presented a challenge. Attempting to apply multiple styles to a single Material-ui component results in no styling being applied. For instance, the following code fails to render any styling: <MenuItem st ...

Tips for creating a highly adaptable code base- Utilize variables

Can anyone help me optimize this lengthy and cumbersome code in HTML and JS? I want to make it more efficient by using variables instead of repeating the same code over and over. In the HTML, I've used href links to switch between different months, w ...