Home > Software engineering >  Change colors based on value
Change colors based on value

Time:12-13

I am currently creating a grade management system and i need your help with a forEach function.

This is my code and i am trying to change the color based on the grade. As you may guessed it's not working. The error that i get is gradeid.forEach is not a function


let gradeid = document.querySelector(".gradeid");
 console.log(gradeid);
 
  gradeid.forEach(function() {
    if ({{grades.0.grade}} >= 5) {
      gradeid.style.color = "#00d629";
    }
  else if ({{grades.0.grade}} < 5 && {{grades.0.grade}} >= 4) {
    gradeid.style.color = "#ffce00";
  } else {
    gradeid.style.color = "#D50000";
  }
  });

Thank you for helping

PS: Dedadline is tomorrow

I tried a lot but failed.

CodePudding user response:

You're using document.querySelector() which returns a single element, that's why you're getting that error. You can't use forEach on a single element. Try using querySelectorAll() to select multiple elements and get a list which can be iterated.

{{grades.0.grade}} This should be an error too. You access it like this: grades[0].grade

CodePudding user response:

You can change your code as below.

let gradeids = document.getElementsByClassName("gradeid");
 console.log(gradeids );

Array.prototype.forEach.call(gradeids, function(gradeid) {
 if ({{grades.0.grade}} >= 5) {
  gradeid.style.color = "#00d629";
 }
 else if ({{grades.0.grade}} < 5 && {{grades.0.grade}} >= 4) {
  gradeid.style.color = "#ffce00";
 } else {
  gradeid.style.color = "#D50000";
 }
});
  • Related