Why does querySelectAll return empty NodeList even though there should be three buttons?

261 views Asked by At

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

There are 2 answers

1
Dimava On BEST ANSWER

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>
1
Klone On

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);
  });
});