Search code examples
javascriptaddeventlistenernodelistqueryselectall

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


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.


Solution

  • 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>