Change html table cell background colour depending on content

I should say I don’t know anything about js really. But I think this is a situation where js would be applicable
I have some php and an output.php webpage.

The webpage basically shows a table with 3 columns, question number, correct answer, student answer.
Works just like I want it to, no problem

What I want to do is, whenever student answer != correct answer, colour that cell red

This doesn’t do the job. I’m not sure how to link the function to the p.a css stuff.

Can you please give me some tips?

<script type="text/javascript" >
function start() {
  paint_cells();
}
function paint_cells() {
	var tds = document.querySelectorAll('tbody td'), i;
	for(i = 0; i < tds.length; i += 3) {
	  if(tds[i+1].textContent == tds[i+2].textContent){
	    tds[i].classList.add("bgyellow");
	  }
	  else if (tds[i+1].textContent != tds[i+2].textContent){
	    tds[i].classList.add("bgred");
	  }
	  else {
	    tds[i].classList.add("bggreen");
	  }
	}

p.a {
        white-space: nowrap;
    }
    h2 {
        text-align: center;
        font-family: Helvetica, Arial, sans-serif;
    }
    table {
        margin-left: auto;
        margin-right: auto;
    }
    table, th, td {
        border: 1px solid black;
        border-collapse: collapse;
    }
    th, td {
        padding: 5px;
        text-align: left;
        font-family: Helvetica, Arial, sans-serif;
        font-size: 90%;
        white-space:nowrap;
    }
    table tbody tr:hover {
        background-color: #dddddd;
    }
    .wide {
        width: 90%;
    }
    .bgred{
    background-color: red; 
  }
  .bggreen{
    background-color: whitesmoke; 
  }
  .bgyellow{
    background-color: yellow; 
  }
 }
  </script>

Well, if any of you out there have to do this, try this, worked for me:

<script type="text/javascript" >
    
function paint_cells() {
  var tds = document.querySelectorAll('tbody td'), i;
  for(i = 0; i < tds.length; i += 3) {
    if(tds[i+1].textContent != tds[i+2].textContent){
      tds[i+2].bgColor = "red";
    }
  }
}

paint_cells();
</script>
1 Like
Sponsor our Newsletter | Privacy Policy | Terms of Service