Home > Blockchain >  How to change color of a class with Javascript
How to change color of a class with Javascript

Time:12-26

I get all movie datas from Firebase and also i get score of the movies. If the score of the movie is higher than 70, then i will change color of the class as "deepskyblue", if it is 50 or higher it will be "orange" and lastly if it is lower than 50 it will be "crimson"(red). When i do this, it only changes my first movie's class's color. But i wanna change all of them. How can i do this?

var movieNo = 0;
let html = '';
var body = document.getElementById('editor');
var body2 = document.getElementById('week');

function AddItemsToTable(name, score, img, id) {
  var movies = `<div ><img src="${img}" ><p><a href="Admin.html?movieId=${id}">${name}</a></p> <p> <i  id="star"></i>&nbsp;<a >${score}</a> </p> </div>`;
  html = movies;

  body.innerHTML  = html;
  body2.innerHTML  = html;

}


function AddAllItemsToTable(TheMovies) {
  movieNo = 0;
  var counter = 0;

  TheMovies.forEach(element => {
    if (counter === 6) {
      return;
    }
    AddItemsToTable(element.movieName, element.movieScore, element.movieImage, element.movieId);
    var i = document.getElementsByClassName("fa fa-star")[element.movieId];
    console.log(i);
    if (element.movieScore >= 70) {
      i.style.color = "deepskyblue"; //good movie

    } else if (element.movieScore >= 50) {
      i.style.color = "orange"; //not bad
    } else {
      i.style.color = "crimson"; //bad movie
    }

    counter  ;

  });

}

function getAllDataOnce() {
  const dbRef = ref(db);
  get(child(dbRef, "Movies"))
    .then((snapshot) => {
      var movies = [];
      snapshot.forEach(childSnapshot => {
        movies.push(childSnapshot.val())
      });
      AddAllItemsToTable(movies);
    });
}
window.onload = getAllDataOnce;
<div  id="body">

  <div >Opening This Week</div>
  <div ><a href="series.html">See all</a></div>
  <div id="week">

  </div>
  <div >Editor's Picks</div>
  <div ><a href="movies.html">See all</a></div>
  <div id="editor">

  </div>


</div>

My Website

enter image description here

Console.log(i) enter image description here

CodePudding user response:

Instead of selecting the elements with class name you can give it a unique id. For th i tags you can give the id as for example id="star${id}"

function AddItemsToTable(name, score, img, id) {
  var movies = `<div ><img src="${img}" ><p><a href="Admin.html?movieId=${id}">${name}</a></p> <p> <i  id="star${id}"></i>&nbsp;<a >${score}</a> </p> </div>`;
  html = movies;

  body.innerHTML  = html;
  body2.innerHTML  = html;

}
 AddItemsToTable(element.movieName, element.movieScore, element.movieImage, 
 element.movieId);
 var i = document.getElementById("#star" element.movieId);

CodePudding user response:

you can just use a style="color:"desired color name/hexcode" easiest way to change color

  • Related