In your current implementation, your code will only work for a word that equals "hello", when that is the first word. document.getElementbyID will return the first element of that id that it finds.
Consider this:
function dynamicTable(word, count) {
var tableRef = document.getElementById("id_table");
tableRef.insertRow().innerHTML = "<td id='id_word'>" + word + "</td>" + "<td id='id_count'>" + count + "</td>";
if (word == "hello") {
document.getElementById("id_word").style.backgroundColor = "green";
}
}
let words = ["hello", "goodbye", "blah", "blah", "hello", "hello", "something"];
words.forEach((word, i) => {
dynamicTable(word, i);
});
The first cell with word in it will have a green background, but no other cells will.
Perhaps you could create the td separately, give it a style conditionally and then add it to the table afterwards, something like this:
function dynamicTable(word, count) {
var tableRef = document.getElementById("id_table");
const cell_word = document.createElement("td");
cell_word.id = "id_word";
cell_word.innerText = word;
if (word === "hello") {
cell_word.style.backgroundColor = "green";
}
const cell_count = document.createElement("td");
cell_count.id = "id_count";
cell_count.innerText = count;
tableRef.insertRow().append(cell_word, cell_count);
}
let words = ["hello", "goodbye", "blah", "blah", "hello", "hello", "something"];
words.forEach((word, i) => {
dynamicTable(word, i);
});
wordandcountso that the code does not produce errors. Note that the value ofwordmust have been"hello"when the code ran, and that only the first cell would become green, because IDs must be unique to the document, otherwise only the first is selected bygetElementById.