Using javascript to change css classes dynamically

Hi there,

I am trying to change the background color of .overview element to either green, yellow or red based on a dynamic number.

How should I set up my CSS or JS differently to achieve those results?

I’ve labeled my element "overview-element:

Here’s what I currently have CSS as.

<style>
    .overview-element.green {
        background-color: green;
    }
    
    .overview-element.yellow {
        background-color: yellow;
    }
    
    .overview-element.red {
        background-color: red;
    }
</style>

And here is my JS:


<script>
// Get the number value
const number = 55; // Replace with your own number value

// Get the element to apply the CSS color
const element = document.getElementById('overview-element'); // Replace with your own element ID

// Remove existing color classes
element.classList.remove('red', 'yellow', 'green');

// Check the number value and add appropriate color class
if (number >= 0 && number <= 40) {
  element.classList.add('red');
} else if (number >= 41 && number <= 75) {
  element.classList.add('yellow');
} else {
  element.classList.add('green');
}
</script>

On the published site I can’t get the background color to change the way I want. What can I do to make this work?


Here is my public share link: Webflow - The Attributes

Change that to

Wow two responses from @PixelGeek! Thank you.

I made the change but still can’t get it to work. Do I need to do something with the class name on the webflow viewer?