Search code examples
javascriptcsstoggleclass

Toggling CSS to change background


In a tic tac toe game, when a game is won, I want the winning line's background to go red.

I have taken the winning line box id's into an array as such-

if (cell1.innerText == symbol && cell2.innerText == symbol) {

if (cell3.innerText == symbol) {
  winningLine=[cell1.id,cell2.id,cell3.id]; //contains the id's of winning line
  winFlag = true;
}
......

Then I add the css when a win is confirmed using this function-

 function addOrRemoveCSS(line){

  var i=0;
  while(i<3){

    var cell=$(line[i]); // This is my main doubt. Can I do this??
    cell.toggleClass("winningCSS");
    i++;

  }
 }

Is there something wrong that Im doing here?? Because there is no change in the background.


Solution

  • Include the # with your ID:

    function addOrRemoveCSS(line){
    
      var i=0;
      while(i<3){
    
        var cell=$("#"+line[i]);
        cell.toggleClass("winningCSS");
        i++;
    
      }
     }
    

    The jQ selector needs to know it's an ID you're looking for. You're just passing the strings without the ID selector #