This is my first project for JS, and I'm tasked with making a table that randomly generates numbers from 1 through 100, and changing the background color of cells that are multiple of 3 to red, and multiples of 2 to blue. I can create the table with random numbers, but don't know how to change the background color of the cell. Here is my code for the table.
// creates a string var that holds the table
var str = "<table border='1'>";
for (row = 0; row < num; row++) {
str += "<tr>";
for (col = 0; col < num; col++) {
str += "<td>";
// creates a random number from 1-100
var randNum = Math.floor(Math.random() * 100) + 1;
str += randNum;
// if a random num is a multiple of 3
if (randNum%3 === 0) {
// make cell have red background
}
// if a random number is a multiple of 2
else if (randNum%2 === 0) {
// make cell have blue background
}
str += "</td>";
}
str += "</tr>";
}
str += "</table>";
I tried setting the < td > with an id=" " and then in the if statement calling it like the, but it doesn't work.
str += "<td id='redOrBlue'>";
// creates a random number from 1-100
var randNum = Math.floor(Math.random() * 100) + 1;
str += randNum;
// if a random num is a multiple of 3
if (randNum%3 === 0) {
// make cell have red background
document.getElementById('redOrBlue').style.backgroundColor='red';
}
// if a random number is a multiple of 2
else if (randNum%2 === 0) {
// make cell have blue background
document.getElementById('redOrBlue').style.backgroundColor='blue';
}
str += "</td>";
Any help would be appreciated.
http://pastebin.com/EueJtT9n - Full program code