I am very confused as to why this is happening. Basically, I am trying to make a word/phrase guessing game, and if the correct button letter matches the letters in the phrase, it uncovers the letter. I need to store the matching(correct) letter inside a variable and return that letter. If the letter guessed is not the correct one, I need the function to return null.
function checkLetter(clickedLetter) {
let letterFound = ""
if (clickedLetter.tagName == "BUTTON"){
clickedLetter.className = "chosen";
clickedLetter.setAttribute("disabled", "true");
const li = document.querySelectorAll("li.letter")
for (let i = 0 ; i < li.length ; i++){
if (clickedLetter.textContent.toLowerCase() == li[i].textContent.toLowerCase()){
li[i].classList = "show";
letterFound = li[i]
//without this return statement, it runs fine
return letterFound
} else {
//without this return statement, it runs fine
return null
}
}
}
}
qwerty.addEventListener("click", (e) => {
const clickedLetter = e.target;
checkLetter(clickedLetter);
});
https://jsfiddle.net/y4q7ot68/1/ Here is a jfiddle demo with the return statements commented out, working. If you uncomment the return statements, it gets all whacky and doesn't uncover any letters and/or all of the letters. What am I doing wrong?