skip to Main Content

In javascript file, I select same class element with query selector all like this…

const buttons = document.querySelectorAll(".button");

In html file, I wrote like this…

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="index.css">
  </head>
  <body>

    <script src="index.js"></script>
    
    <button class="button" value="rock" style="background-color: rgb(240, 20, 20)"></button>

    <button class="button" value="paper" style="background-color: rgb(20, 240, 20)"></button>
    
    <button class="button" value="scissor" style="background-color: rgb(20, 20, 240)"></button>

  </body>
</html>

After I select the elements, I try to console the "buttons". But what I got is nodelist(0). You can see it in following image…

enter image description here

I watched all the tutorial and learned how to do this. I did the exactly the same but the outcome is not what I expected. Can anyone tell me did I make a mistake or did I need to add something?

2

Answers


  1. import js script file footer.

    and wait to DOM load

    document.addEventListener("DOMContentLoaded", function(){
        const buttons = document.querySelectorAll(".button");
        console.log(buttons);
    });
    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link rel="stylesheet" href="index.css">
      </head>
      <body>
    
        
        <button class="button" value="rock" style="background-color: rgb(240, 20, 20)"></button>
    
        <button class="button" value="paper" style="background-color: rgb(20, 240, 20)"></button>
        
        <button class="button" value="scissor" style="background-color: rgb(20, 20, 240)"></button>
          <script src="index.js"></script>
    
      </body>
    </html>
    Login or Signup to reply.
  2. You can use node as array
    Because all .button same class Name in ALl button that’s why all Button are in one NodeList

    you can access NodeList by indexing. just like buttons[0] or buttons[1]or buttons[2]

    const buttons = document.querySelectorAll(".button");
    console.log(buttons[2])
    

    this code console blue button

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search