Updating CSS in JS code

I wanted to know why the first code did not work but the second did:

Goal - to update table’s cell’s text color if value of text in cell is NOT “OK”.

First try:

function generateTable(table, data) {

  for (let element of data) {

    let row = table.insertRow();

    for (key in element) {

      let cell = row.insertCell();

      let text = document.createTextNode(element[key]);

      text !== "OK"

        ? (cell.style.color = "red")

        : (cell.style.color = "black");

      cell.appendChild(text);

    }

  }

}

Second try:

function generateTable(table, data) {

  for (let element of data) {

    let row = table.insertRow();

    for (key in element) {

      let cell = row.insertCell();

      let text = document.createTextNode(element[key]);

      element[key] !== "OK"

        ? (cell.style.color = "red")

        : (cell.style.color = "black");

      cell.appendChild(text);

    }

  }

}

The difference was in this line:
text !== "OK" ? (cell.style.color = "red") : (cell.style.color = "black");

versus

element[key] !== "OK" ? (cell.style.color = "red") : (cell.style.color = "black");

Shouldn’t they have given me the same results? The first one resulted in all the cells being red. The second one resulted in just the cells without “OK” being red.

This line is the difference. Then, when you do the strict inequality check (!==), it isn’t coercing from a textNode to text. At least, I think that’s what happens.

1 Like