0

I am trying to store value of a button when it is clicked out of multiple buttons but when I am console logging the variable it says undefined.

const getBtn = document.querySelectorAll('button')
const playerSelection = getBtn.forEach((item) => {
  item.addEventListener('click', function(e) {
    return e.target.textContent
  })
})
console.log(playerSelection)
    <body>
      <div id="buttons">
        <button id="rock">ROCK</button>
        <button id="paper">PAPER</button>
        <button id="scissor">SCISSOR</button>
      </div>
      <p id="output"></p>
    </body>

When I am console logging "e.target.textContent" then it's working but not when I am console logging playerSelection.

user229044
  • 232,980
  • 40
  • 330
  • 338
  • The structure of your code is incorrect. You can't `return` from inside your event handlers, and expect that value to propagate back into `playerSelection`. Those two lines of code execute at completely different times. Even if this *did* work, you're assigning the result of `forEach`, which has nothing to do with the event handlers themselves. Instead your `console.log` (and whatever other business logic) have to go *in* the event handler, not outside it. – user229044 Jun 11 '22 at 03:02
  • Thanks. What's the correct way to store the value of button clicked in playerSelection variable?@user229044 – Kaustubh71 Jun 11 '22 at 03:13

0 Answers0