-1

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.

mauri
  • 3
  • 3
  • 2
    Does this answer your question? [Get all elements containing a class with querySelector](https://stackoverflow.com/questions/52365938/get-all-elements-containing-a-class-with-queryselector) – 0stone0 May 04 '23 at 10:47
  • I hoped it would but no, or then I really don't get it. I've tried everything I've found in here and i've tried the above code with const buttons = document.querySelectorAll('.button'); and const buttons = document.querySelectorAll('button'); but neither works.. – mauri May 04 '23 at 11:43
  • sounds like you are selecting the elements before they exist on the page. – epascarello May 04 '23 at 12:04
  • 1
    https://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element – epascarello May 04 '23 at 12:05
  • That was the problem, thank you! – mauri May 04 '23 at 13:04

2 Answers2

0

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);
  });
});
Klone
  • 290
  • 1
  • 2
0

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>
Dimava
  • 7,654
  • 1
  • 9
  • 24
  • That was the problem, thank you! I solved it by adding window.onload function around the JS block. – mauri May 04 '23 at 13:06