-1

In my example I am trying to loop through a collection of HTML elements and check to see if they match a button click on screen. But the loop only seems to check the first html element and does not run the function again if another button is clicked.

keyboard.onclick = function(event) {
  event.target.className += " chosen";
  let letterFound = event.target.innerHTML;
  checkLetter(letterFound);
}

const checkLetter = (a) => {
  let letterCheck = document.querySelectorAll('.letter');

  for (i = 0; i < letterCheck.length; i++) {
    if (a === letterCheck[i].innerHTML) {
      letterCheck[i].className += " show";
      let letterMatch = letterCheck[i];

      return letterMatch
    } else {
      return null;
    }
  }
}
1
  • 6
    You've got return statements in your loop. They cause the enclosing function to exit. Commented Jul 30, 2018 at 14:02

1 Answer 1

1

I would use filter function from es6 to achieve this and solve this in a more functional approach. Hence if you need to support legacy browsers you can use babeljs to transpile code. Basically there is nothing these days that should prevent you from using new js features because with babel you can transpile all.

const matchingLetters = document.querySelectorAll('.letter').filter(elem => elem.innerHtml === a);
// now you can use the filtered array to do something with your matchingLetters.
// e.g. use .map or do some loop etc.
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.