user1580462
user1580462

Reputation: 69

Changing background color for MANY strings based on whether they include a certain word?

I'm trying to check if a bunch of strings have a certain word. If an individual member of that class has the specified word ('unlikely'), then I change background color to green. If an individual member of that class doesn't, then background color is red. So the end result will be a bunch of members of the class with a green background and others with a red background.

My code is not working.

Here's what I've tried.

function colorCoding() {
    var str = document.getElementsByClassName("colorString").innerHTML;
    var n = str.includes("unlikely");
    if (n==true) {
      document.getElementById("colorString").style.backgroundColor = "green";
    } else {
      document.getElementById("colorString").style.backgroundColor = "red";
    }
}

The background color is not changing at all.

I've tried doing it for each individual ID—and it worked—but that would take me forever to go through each member of the class and create a function based on their individual ID. Is there any way to do it with the class? Or without the class, but still using one function for the entire set?

Thanks for your help!

Upvotes: 0

Views: 59

Answers (1)

user12137152
user12137152

Reputation: 697

The problem is with document.getElementsByClassName("colorString").innerHTML. You must include the index. It should be like document.getElementsByClassName("colorString")[0].innerHTML.

document.getElementsByClassName() returns an array of elements with that class name.

For loop:-

 var i;

 var str = document.getElementsByClassName("colorString");
 for (i = 0; i < str.length; i++) {

    if(str[i].innerHTML.includes("unlikely")) { 
      str[i].style.backgroundColor = "green";
  } else {
  str[i].style.backgroundColor = "red";
}

 }

Upvotes: 1

Related Questions