I am trying to store the text of a button in a variable or function that i can use later. So it should be in the global scope i suppose. But i can’t figure out how to do that because if I console.log the function it shows undefined. I’m supposing it’s because the main function doesn’t actually return anything, the nested one does. I was thinking about giving names to the nested functions but i can’t figure out how to name these forEach and eventListener functions or if that would even help me. I am so lost. Please send help
function choice() {
document.querySelectorAll('.container').forEach((button) => {
button.addEventListener('click', (event) => {
let playerChoice = event.target.textContent;
return playerChoice;
});
});
}
console.log(choice());
<div class="container">
<button class="rock">rock</button>
<button class="paper">paper</button>
<button class="scissors">scissors</button>
</div>
If instead i console.log the playerChoice and then i call the function it works but from what i know i can’t store that result.
2
Answers
You can store the value in a global variable. But it won’t be available to log until after the user clicks, so you need another event listener to show that.
If you want to keep it in global variable, then declare the variable and set the value while you are clicking it. I have also gave you another function,
getPlayerChoice
as optional if you want to call any function to do certain things you can do in that way –