Help with Paper, Scissors, Rock DOM manipulation

Hey guys,

So, I have my buttons laid out in the HTML like so:

    <div class="button">
      <h2>Do you choose Paper, Scissors or Rock?</h2>
      <button id="Paper">Paper</button>
      <button id="Scissors">Scissors</button>
      <button id="Rock">Rock</button>
    </div>

And when I have this written into my JS file;

function playerSelection() {
  const buttons = document.querySelectorAll('button');
  buttons.forEach((button) => {
    button.addEventListener('click', (e) => {
    alert(button.id);
    });
  });
};

let playerPlay = playerSelection()

It successfully alerts the id of the buttons, just as I’d expect it to. But when I change that to return(button.id), and assign the id to the variable playerPlay, it returns ‘undefined’ when I console.log it. Is there something I’m missing, like converting the ID to a string, or should I be converting the nodelist to an array and then using an if/else statement? I’m really stumped

Cheers

Hey, Im also a beginner so I dont know if this will work but maybe you should try moving the event listener out of the function and assigning the button id to a global variable:

let playerChoice;

buttons.forEach((button) => {
    button.addEventListener('click', playerSelection);
});

function playerSelection(e) {
    playerChoice = button.id;
}

I dont know how to explain why this would work, but it could be because the computer doesnt know when to call the function playerSelection

This ALMOST worked. I changed it a bit so it looked like this:

let playerChoice;

const buttons = document.querySelectorAll('button');
buttons.forEach((button) => {
  button.addEventListener('click', playerSelection);
});

function playerSelection(e) {
    playerChoice = button.id;
}

But now it says that it can’t find the variable “button” on line 14, which is the playerChoice = button.id

Just in case anyone gets stuck on this in the future, this got my code to work:

let playerChoice;

const buttons = document.querySelectorAll('button');
buttons.forEach((button) => {
  button.addEventListener('click', (e) => {
    playerChoice = (button.id)
  });
});