skip to Main Content

I’m trying to add event listeners to all buttons in my program, but const buttons = document.querySelectorAll(‘.button’); returns an empty NodeList.

HTML:

    <div id="buttons" class="buttons">
        <button type="button" class="button" id="send">Send</button>
        <button type="button" class="button" id="delete">Delete</button>
        <button type="button" class="button" id="again">Again</button>
    </div>

JS:

const buttons = document.querySelectorAll('.button');
buttons.forEach(button => {
    button.addEventListener("click", function() {
        clickEvent(param);
    });
});

This is what I have and I have no idea why it isn’t working. It should return a NodeList of the buttons but the list is empty.

2

Answers


  1. You are using #button as the selector in document.querySelectorAll(), but your buttons have ids of send, delete, and again. The # selector is used to select elements with a specific id attribute, not elements with a specific class or tag name, so use the class button instead (. is for classes)

    const buttons = document.querySelectorAll('.button');
    buttons.forEach(button => {
      button.addEventListener("click", function() {
        clickEvent(param);
      });
    });
    
    Login or Signup to reply.
  2. You are running <script> before the <div id="buttons"> gets inserted into the document
    Use <script defer src="..."> or place script in the end of <body> to avoid that

    <script> console.log(document.quserySelectorAll('a')) // [] </script>
    <a> This is A </a>
    <script> console.log(document.quserySelectorAll('a')) // [<a>] </script>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search