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

Navigating through the year selection with your keyboard

By default, a dropdown menu containing years allows for keyboard navigation. For example, if you type in 1992 while the dropdown is selected, it will automatically move to that specific year option. I am curious to know if there is a way to activate a two ...

Modifying the status using retrieved JSON information

My goal is to retrieve data from an external API and use it to update the state of my app. Although I can see the data in the console, the state of my app remains unchanged when I try to run setState. class App extends Component { state={ jobs:[] ...

When using Vue.js router.push, the URL gets updated but the RankerDetail component does not refresh when navigating with a button

I am currently working on a Vue.js project that involves vue-router, and I've encountered an issue with the RankerDetail component. This particular component is responsible for dynamically displaying data based on the route parameter id. Strangely, wh ...

What is the best method for locating X-Path for elements inside a frameset?

I need help creating a test case for Selenium because I am struggling to locate elements on my website. The issue seems to be related to the fact that my site uses an HTML frame set. When I try to select all links using Firebug: //a I do not get any res ...

Tips for using a JavaScript function to navigate to a specific division (<div>) on an HTML page

I am facing an issue where I need to redirect within the same HTML page that includes a add-form div. What I want is that when I click on a button, my redirection should be to a specific div containing some code. Currently, I have code that redirects to a ...

The response from a jQuery ajax call to an MVC action method returned empty

I am working on an inventory application with the following layout: <body> <div class="container" style="width: 100%"> <div id="header"> blahblahblah </div> <div class="row"> <div id="rendermenu ...

Information on the Manufacturer of Devices Using React Native

Struggling to locate the device manufacturer information. Using the react-native-device-info library produces the following output. There seems to be an issue with handling promises. I need to store the device manufacturer value in a variable. const g ...

Create a link for editing in a data table that can filter based on multiple column values and also enable global search on specific custom

How can I generate an edit link with a function that requires multiple parameters extracted from different data columns received via ajax? I have come across the render callback, but it seems to only return one column value at a time and my requirement is ...

Ways to modify the gap between buttons using CSS

I am faced with a design challenge on my home page. I want to add some spacing between the buttons so they are not too close to each other, but for some reason margin-top and margin-bottom properties are not working as expected. Can you help me figure out ...

JavaScript: Remove just the specific user input without affecting the rest of the HTML block

I'm facing a dilemma with deleting a specific user input without removing the entire HTML block. I know that the delete button triggers on the HTML ID 'noteDelete', which is the parent of each user input. However, I'm unsure about how t ...

Utilizing React JS to dynamically incorporate form values into objects

I have an array of objects where I need to add a key value State : const [row, setRow] = useState([{ nameofthework: "", schedulerefNo: "", unitprice: "", qty: "", uom: "", gst: "", total: "& ...

keep jquery scrolltop position consistent after receiving response

I created a code to show the chat history, and everything seems to be working fine. However, I encountered an issue where old posts are displayed all at once when scrolling up the div. In order to continue scrolling smoothly, I included this code $("#messa ...

I am perplexed by the driver's inability to locate the element

Check out this webpage for the latest updates: I am attempting to extract data on EPS, EPS beat, GEPS, GEPS beat, and revenue from this site. List1 = driver.find_element_by_xpath("""/html/body/div[2]/div[1]/div/main/div[2]/div[3]/div[2]/sec ...

React component fails to display content following execution of Jquery Ajax request

Utilizing a basic jQuery ajax function to retrieve inline HTML code from an API $.ajax({ url: url, headers: { 'Accept': 'application/javascript' }, dataType: 'html', beforeSend: function(){ $('.load-mor ...

Dealing with errors in Next.js when using axios in Express

Currently, I am working on implementing the login feature for my application using an asynchronous call to my API. The issue I am facing is that despite express throwing an error, the .then() function is still executing with the error instead of the actual ...

How can I extract the value of a JavaScript variable using jsoup in an HTML document?

<html> <script type="text/javascript"> var map = null; jQuery(function($) { L.marker([50.065407, 19.945104], {title: 'Cat'}) .bindPopup('<h3>Cat</h3> ...

The utility of commander.js demonstrated in a straightforward example: utilizing a single file argument

Many developers rely on the commander npm package for command-line parsing. I am considering using it as well due to its advanced functionality, such as commands, help, and option flags. For my initial program version, I only require commander to parse ar ...

The use of Angular's ngClass directive does not work within the link function

I have a straightforward directive that renders an element, and this is the template: <div class="nav-item"></div> The .nav-item class looks like this: .nav-item { height: 50; } Here's the directive in action: angular.module('m ...

Troubleshooting imagejpeg() Function Failure in PHP Server

I've been working on implementing image cropping functionality for my website. I've managed to send an array of cropped image dimensions (x, y, width, height) to my PHP script. On my localhost, the script successfully crops the image, but unfort ...

The styles applied to the Angular 5 Component host element are not being reflected correctly in jsPlumb

As a beginner in Angular >2 development, I am excited to build my first application from scratch. One of the features I'm trying to implement is drawing flow charts using jsPlumb. However, I have encountered an issue where the connectors are not being ...