0

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.

2 Answers2

0

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

Juljo Shahini
  • 138
  • 10
  • Thank you for your help! Unfortunately it doesn't work. The error is: 5:51 Uncaught TypeError: Cannot set properties of undefined (setting 'color') at 5:51:25 at NodeList.forEach () at 5:44:11 I added a value to each grade to then access it in the script but it's still undefined How can i access multiple values of a html document? – HelpNeeded Dec 13 '22 at 10:38
0

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";
 }
});