I have a code that's supposed to show the table cell value when clicked on and also highlight the table cell that has been clicked on (Using CSS class). However, the table cell isn't highlighting for some reason. It works when I remove the table cell value code. I'm not sure what's wrong.
const myWords = ["LOL", "HEY", "TOYS", "YES", "SIR", "JOY"];
//Highlighting Table Cell code
//Goes through every 'td' on page
for (let node of document.querySelectorAll("td")) {
node.onclick = function() {
if (node.className == "") {
node.className = "selected"
} else {
node.className = ""
}
}
}
//Get Table Value code
var selectedWord = "";
var clicking = document.getElementsByTagName('td');
//Everytime the user click on a cell...
for (var i = 0; i < clicking.length; i++) {
var click = clicking[i];
click.onclick = function() {
selectedWord += this.innerHTML;
alert(selectedWord);
//Calls a function for each word in myWords
myWords.forEach(myFunction);
function myFunction(item, index) {
//If a word matches the selected word...
if (item == selectedWord) {
alert(item);
}
}
}
}