Attempting to transform a numerical value into CSS syntax

Currently, I am attempting to loop through several DIV elements, extract a numerical value from each DIV, and then based on that value matching a specific value in the JavaScript code, assign a particular CSS Class back to the original DIV.

This is the snippet of code I have been working on:


const getRating = document.getElementsByClassName('my-ratings');
let getRatingValues = [];
for(var i = 0; i < getRating.length; i++) {
    getRatingValues += getRating[i].textContent;

    if (getRatingValues == 5) {
        getRating.classList.add('rating-5');
    }
    if (getRatingValues == 4) {
        getRating.classList.add('rating-4');
    }
    if (getRatingValues == 3) {
        getRating.classList.add('rating-3');
    }
    if (getRatingValues == 2) {
        getRating.classList.add('rating-2');
    }
    if (getRatingValues == 1) {
        getRating.classList.add('rating-1');
    }
}

I feel like I am very close to solving this issue, but just can't quite figure it out...

Currently, it appears that the script is treating the values in getRatingValues as a string. For example, if I have values of 5, 3, 1, 2, 2, 4 in my DIVs, the getRatingValues will be '531224'. Can someone please help guide me in the right direction?

Answer №1

Keeping it DRY - convert to numbers:

let totalRatings = 0;
document.querySelectorAll('.my-ratings').forEach(function(rating) { // iterate through ratings
  let value = rating.textContent; // retrieve the rating value
  totalRatings += isNaN(value) ? 0 : +value; // check if value is a number and add it to total
  rating.classList.add('rating-' + value); // should this be added outside the loop?
})

I personally believe

getRating.classList.add('rating-'+val);
should be placed outside the loop to avoid adding multiple classes on the same element.

In order to support IE, you can use:

var allRatings = document.querySelectorAll('.my-ratings');
for (var j=0; j<allRatings.length; j++) {
  let value = allRatings[j].innerText;
  let rateElement = allRatings[j];

Answer №2

To solve this issue, you must ensure that the string is converted to a Number.

Revise

getRatingValues += getRating[i].textContent;

with

getRatingValues += Number(getRating[i].textContent);

Furthermore, do not initialize your getRatingValues to []; instead, set it as

let getRatingValues = 0;

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

The element type is not valid: it should be a string for built-in components or a class/function for composite components, but it is currently an object in a React project

In the process of developing a React app to explore MUI capabilities, I encountered an error in my browser: The issue reported is: Element type is invalid - expected a string (for built-in components) or a class/function (for composite components), but rec ...

Iterate through a directory on the local machine and generate elements dynamically

I am looking to create a jQuery-UI tabs menu that includes 54 images on each tab. I have a total of 880 images stored in a folder, and it would be very time-consuming to manually insert an <img> tag for each one. Is there a way to dynamically cycle t ...

Having trouble getting SCSS to function properly? (Updated Code)

Transitioning from CSS to SCSS is my current project. I decided to make the switch because of SCSS's nesting capabilities, which I find more convenient for coding. However, I'm facing some challenges getting it to work properly. In my regular CSS ...

Mastering the art of carousel div creation with Bootstrap

Is there a way to create a carousel in Bootstrap 3 where only one div slides at a time, instead of three? I attempted to use divs instead of images in the traditional carousel structure, but it's not functioning as expected. I'm looking for some ...

Ways to differentiate between buttons in a button cluster?

I have created a set of 3 buttons using the code from this resource. However, the buttons are currently positioned vertically close to each other as shown in the source code. I would like to adjust the spacing between them. Is there a way to achieve this ...

Hover-activated dropdown menu

After reading numerous tutorials and spending hours trying to create a submenu on hover, I still can't seem to get it to work. My goal is to display "Zimmer", "Reservierung", and "Preise" in a vertical menu when hovering over "Hotel," and so on. Here ...

In order to add value, it is necessary to insert it into the text box in HTML without using the "on

example <input type="text" id="txt1" onChange="calculateTotal();" /> <input type="text" id="txt2" onChange="calculateTotal();" /> <input type="text" id="txt3" onChange="updateValue();" readonly/> <input type="text" id="txt4" onChange= ...

Inconsistency in field generation in WordPress Contact Form 7 causing issues

After utilizing the WordPress plugin Contact Form 7 to put together a straightforward questionnaire, I discovered that two fields, Your Birthday and Your Email, were mistakenly generated on top of one another in the final output. You can take a look at th ...

The image must be able to fit within the div container without distorting its proportions

Recently, I created a slider that functions flawlessly. However, I am struggling to make the image fit inside the div without distorting its proportions. I've tried various methods but haven't been able to achieve the desired result. Could you p ...

What could be causing the dysfunction of the jQuery class adding function?

I'm new to using jQuery and I'm trying to add a class to the 'a' tag when the 'li' tag is clicked. However, it doesn't seem to be working as expected. $('.nav-item').click( function() { $(".nav-item a").re ...

How can we avoid re-rendering the same component repeatedly when using React Router v6?

As a beginner in react, I'm facing an issue with preventing components from re-rendering when navigating to a different page. Specifically, I want to display only text on my Signup and Login pages, but the Navbar keeps re-rendering every time I switch ...

Struggling to access FormData in php

I'm having trouble retrieving variables from FormData in PHP after making an AJAX call. What could be causing this issue? Here is the snippet of my JavaScript code: var sendData = new FormData(); sendData.append('itemid',$('select#sel ...

Exiting a NodeJs function entirely rather than just returning from an internal function

There is a function in my code app.post('/assignment/loan', (req, res) => { Within that function, there is another function db.run('SELECT loanable FROM book WHERE id=?',[bookID],(err,row)=>{ I tried using return but it only exi ...

Ways to exhibit API information leveraging the prowess of Ajax

I am looking for a way to utilize the API in order to present data in an organized manner, similar to the following example: Job Title: Agricultural and Related Trades Percentage of Occupancies in Area: 15.41% Unfortunately, my attempt to showcase the d ...

Aligning Text to the Right Using CSS

HTML <body> <div class="menu_items"> <h1>My Heading</h1> <nav> <a>Item 1</a> <a>Item 2</a> <a>Item 3</a ...

The hover state of a div will not be lost if its parent element is not being hovered over

When hovering over the second, third, or fourth item, hidden text will appear on the left side. If you hover your cursor over the hidden text, it will disappear again. I want to be able to hover over the second item, move my cursor to "hide", and click o ...

Learn how to call class methods using jQuery events by utilizing the on() method

I'm attempting to create a reusable "component" using both HTML5 and accompanying JavaScript code that can be utilized multiple times. First, let's examine the HTML5 component code: <div class="listEditor" id="myStringList"> <div id="li ...

Unique Symbols and Characters in JavaScript

My JavaScript code looks like this: confirm("You are selecting to start an Associate who is Pending Red (P RD) status. Is this your intent?") I am encountering a strange issue where I get an alert with special characters, even though my code does not con ...

Create a rectangular container with text using CSS

Looking to achieve a square box design using CSS with specific dimensions? Want to insert text inside the square and ensure it is horizontally centered within the square? Check out this code snippet: #myid { width: 100px; height: 100px; ...

IE does not render the output of multiple AJAX requests

Desiring an autocomplete feature for an input box that displays results in a div below it, I wrote this shortened code. It functions flawlessly on Chrome and Firefox - when searching for "Eggs" and then "Milk", their respective results appear. However, Int ...