0

I want my button's class name to show up when I click on it, but nothing is showing up.

const buttons = document.querySelectorAll("button");
buttons.forEach((button) => {
    button.addEventListener('click', () => {
        console.log(button.className);
    })
})
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <title>Rock Papers Scissors</title>
        <link rel="stylesheet" href="styles.css" />
        <script src="javascript.js"></script>
    </head>
    <body>
        <h1>Rock Paper Scissors</h1>
        <button class="rock">Rock</button>
        <button class="paper">Paper</button>
        <button class="scissors">Scissors</button>
    </body>
</html>

I've omitted some of the full code, but you can find it here if required: https://github.com/pranit-garg/odin-rock-papers-scissors

Thanks so much for the help in advance!

Hao Wu
  • 17,573
  • 6
  • 28
  • 60
pranitgarg
  • 15
  • 4

1 Answers1

3

Move the script tag just before the end of the body section. If its in the head, and you do not delay its execution until page load with adding an event listener to the window, then it won't bind to any buttons because there are no buttons yet when your code is executed, as it executes in the head, when body part of your document is not yet rendered.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <title>Rock Papers Scissors</title>
        <link rel="stylesheet" href="styles.css" />
    </head>
    <body>
        <h1>Rock Paper Scissors</h1>
        <button class="rock">Rock</button>
        <button class="paper">Paper</button>
        <button class="scissors">Scissors</button>
        <script src="javascript.js"></script>
    </body>
</html>
jaboja
  • 2,178
  • 1
  • 21
  • 35
  • 1
    that works, thanks for the help! Another solution I found that might be helpful to others is adding "defer" to the script tag to rewrite it as: that way I can keep the code in the head – pranitgarg Sep 13 '22 at 10:48