Herman Lee Tzer Her Herman Lee Tzer Her - 5 months ago 8
HTML Question

Javascript colors and tables?

I'm doing revision in preparation for my Web Development exam, and came across this question:enter image description here

My answer:

function pallete() {
var components = ["00", "33", "66", "99", "CC", "FF"];
var context = document.body;
var tab = document.createElement('table');
for (i = 0; i < 6; i++) {
for (j = 0; j < 6; j++) {
var trow = document.createElement('tr');
for (f = 0; f < 6; f++) {
var thead = document.createElement('th');
thead.innerHTML = "#" + components[i] + components[j] + components[f];
thead.style.color = components[i] + components[j] + components[f];
trow.appendChild(thead);
}
tab.appendChild(trow);
}
}
context.appendChild(tab);
}


I tested the code on the browser, but nothing is coming up! I think my logic is perfect though... Not sure what went wrong here. Please give me any pointers, thank you very much!

Answer

Working example with

  • declaration block at top of function
  • document.createElement
  • td instead of th
  • innerHTML as assignment
  • td.style.backgroundColor instead of td.style.color
  • assignment to color needs # in front of color values, like #003366

function pallete() {
    var components = ["00", "33", "66", "99", "CC", "FF"],
        context = document.body,
        tab = document.createElement('table'),
        trow, td,
        i, j, f;

    for (i = 0; i < 6; i++) {
        for (j = 0; j < 6; j++) {
            trow = document.createElement('tr');
            for (f = 0; f < 6; f++) {
                td = document.createElement('td');
                td.innerHTML = "#" + components[i] + components[j] + components[f];
                td.style.backgroundColor = "#" + components[i] + components[j] + components[f];
                trow.appendChild(td);
            }
            tab.appendChild(trow);
        }
    }
    context.appendChild(tab);
}
<body onload="pallete();"></body>

Comments